@@ -12,23 +12,48 @@ Hook that returns true when the media query matches.
1212function useMediaQuery(mediaQueryOrVariableName : string , defaultValue = false ): boolean ;
1313```
1414
15- ## Usage
15+ ## Using a media query string
1616
17- Define the media query in your CSS variables.
17+ Use the hook in your component using a media query string.
18+
19+ ``` tsx
20+ function DemoComponent() {
21+ const isMinWidth480px = useMediaQuery (' (min-width: 480px)' );
22+
23+ return <div >{ isMinWidth480px ? ' large' : ' small' } </div >;
24+ }
25+ ```
26+
27+ ## Using a CSS variable
28+
29+ To use the hook in your component using the CSS variable, define the media query in your CSS
30+ variables.
1831
1932``` css
2033:root {
2134 --min-width-480 : (min-width: 480px );
2235}
2336```
2437
25- Use the hook in your component using the CSS variable or a custom media query.
38+ Use the media query variable as the first argument.
39+
40+ ``` tsx
41+ function DemoComponent() {
42+ const isMinWidth480px = useMediaQuery (' --min-width-480' );
43+
44+ return <div >{ isMinWidth480px ? ' large' : ' small' } </div >;
45+ }
46+ ```
47+
48+ ## Server-side rendering
49+
50+ The hook returns the default value when the ` matchMedia ` API is not available (for example in
51+ server-side rendering). Set a default value if you get hydration mismatch errors.
2652
2753``` tsx
2854function DemoComponent() {
29- const isMinWidth480pxUsingVar = useMediaQuery (' --min-width-480' );
30- const isMinWidth480pxUsingQuery = useMediaQuery (' (min-width: 480px)' );
55+ const isMinWidth480px = useMediaQuery (' (min-width: 480px)' , true );
3156
32- return <div >{ isMinWidth480pxUsingVar && isMinWidth480pxUsingQuery ? ' large' : ' small' } </div >;
57+ return <div >{ isMinWidth480px ? ' large' : ' small' } </div >;
3358}
3459```
0 commit comments