react-use/docs/useMedia.md
Teague Stockwell 5c01189412
fix: useMedia SSR hydration bug with defaultState (#2216)
* 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
2021-12-30 15:31:24 +01:00

30 lines
864 B
Markdown

# `useMedia`
React sensor hook that tracks state of a CSS media query.
## Usage
```jsx
import {useMedia} from 'react-use';
const Demo = () => {
const isWide = useMedia('(min-width: 480px)');
return (
<div>
Screen is wide: {isWide ? 'Yes' : 'No'}
</div>
);
};
```
## Reference
```ts
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](https://reactjs.org/docs/react-dom.html#hydrate) for more on why this is can lead to costly bugs 🐛.