Installation
Props
| Prop | Type | Default | Description |
|---|---|---|---|
query | string | undefined | The media query to track. (required) |
defaultState? | boolean | undefined | The default state of the media query. (optional) |
Key Features & Details
SSR & Initial Values
- The hook uses
defaultStateas the initial value during SSR or if the browser is not available. - If
defaultStateis not provided, the initial value isfalseon the server and the actual match on the client. - A warning is logged in development if
defaultStateis not provided during SSR, to help prevent hydration mismatches.
Required Query
- The
queryprop is required and must be a non-empty string. - The hook throws an error if
queryis missing or invalid.
State Updates
- The hook updates its state immediately on mount and whenever the media query changes.
- Uses the
changeevent onwindow.matchMediafor real-time updates.
Cleanup
- The event listener is removed automatically when the component unmounts or the query changes.
Caveats & Best Practices
- Always provide a
defaultStatefor 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
defaultStateorfalse.
Examples
Basic Usage
const isLarge = useMedia('(min-width: 1024px)');
return <div>{isLarge ? 'Large screen' : 'Small screen'}</div>;With Default State (SSR-safe)
const isDark = useMedia('(prefers-color-scheme: dark)', false);Responsive Component
function ResponsiveComponent() {
const isTablet = useMedia(
'(min-width: 768px) and (max-width: 1023px)',
false,
);
return <div>{isTablet ? 'Tablet view' : 'Other view'}</div>;
}