useMedia
Tracks the window's current media query.
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
defaultState
as the initial value during SSR or if the browser is not available. - If
defaultState
is not provided, the initial value isfalse
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 onwindow.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
orfalse
.
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>;
}