mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
* fix: useMedia SSR hydration bug with defaultState Prevent a React hydration mismatch when a default value is provided by not defaulting to window.matchMedia(query).matches. * Refactor nested ifs
864 B
864 B
useMedia
React sensor hook that tracks state of a CSS media query.
Usage
import {useMedia} from 'react-use';
const Demo = () => {
const isWide = useMedia('(min-width: 480px)');
return (
<div>
Screen is wide: {isWide ? 'Yes' : 'No'}
</div>
);
};
Reference
useMedia(query: string, defaultState: boolean = false): boolean;
The defaultState parameter is only used as a fallback for server side rendering.
When server side rendering, it is important to set this parameter because without it the server's initial state will fallback to false, but the client will initialize to the result of the media query. When React hydrates the server render, it may not match the client's state. See the React docs for more on why this is can lead to costly bugs 🐛.