use-media (use-media)
Tracks the window's current media query.
v0.1.0
Usage
import { use-media } from "@/hooks"
1"use client";
2
3import {
4 Card,
5 CardContent,
6 CardDescription,
7 CardFooter,
8 CardHeader,
9 CardTitle,
10} from "@/components/ui/card";
11
12import { useMedia } from "@/components/hooks/use-media";
13
14export function UseMediaDemo() {
15 const isMobile = useMedia("(max-width: 768px)");
16 const isDesktop = useMedia("(min-width: 768px)");
17
18 return (
19 <Card className="relative max-w-sm w-full">
20 <CardHeader>
21 <CardTitle>useMedia</CardTitle>
22 <CardDescription>
23 This component uses the <code>useMedia</code> hook to check if the
24 current window matches a media query.
25 </CardDescription>
26 </CardHeader>
27 <CardContent>
28 <p>Is mobile: {isMobile ? "Yes" : "No"}</p>
29 <p>Is desktop: {isDesktop ? "Yes" : "No"}</p>
30 </CardContent>
31 <CardFooter>
32 <p className="text-sm text-muted-foreground">
33 Change the window size to see the values changing.
34 </p>
35 </CardFooter>
36 </Card>
37 );
38}
39
Install
npx wkkkis-hooks add use-media
Options
Name | Type | Default | Description |
---|---|---|---|
query | string | undefined | The media query to track. (required) |
defaultState? | boolean | undefined | The default state of the media query. (optional) |
SSR & Initial Values
- The hook uses defaultState as the initial value during SSR or if the browser is not available.
- If defaultState is not provided, the initial value is false on the server and the actual match on the client.
- A warning is logged in development if defaultState is not provided during SSR, to help prevent hydration mismatches.
Required Query
- The query prop is required and must be a non-empty string.
- The hook throws an error if query is missing or invalid.
State Updates
- The hook updates its state immediately on mount and whenever the media query changes.
- Uses the change event on window.matchMedia for real-time updates.
Cleanup
- The event listener is removed automatically when the component unmounts or the query changes.
Caveats & Best Practices
- Always provide a defaultState for SSR to avoid hydration mismatches.
- The hook returns a boolean indicating whether the media query currently matches.
- The hook is intended for use in the browser; on the server, it will always return the defaultState or false .
Files in this hook
Source | Destination |
---|---|
files/use-media.ts | src/hooks/use-media.ts |