h3/use's logo

h3/use

Command Palette

Search for a command to run...

useMedia

Tracks the window's current media query.

useMedia
This component uses the useMedia hook to check if the current window matches a media query.

Is mobile: No

Is desktop: No

Change the window size to see the values changing.

Installation

Props

PropTypeDefaultDescription
querystringundefinedThe media query to track. (required)
defaultState?booleanundefinedThe 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 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.

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>;
}