From a57fb0325e7f67db5e1e994e74715ccb991a178f Mon Sep 17 00:00:00 2001 From: Ward Oosterlijnck Date: Tue, 16 Jul 2019 19:07:39 +1000 Subject: [PATCH 1/2] Isomorphic useMedia --- src/useMedia.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/useMedia.ts b/src/useMedia.ts index ae3968c314..053eb21f3c 100644 --- a/src/useMedia.ts +++ b/src/useMedia.ts @@ -1,7 +1,8 @@ import { useEffect, useState } from 'react'; +import { isClient } from './util'; -const useMedia = (query: string) => { - const [state, setState] = useState(() => window.matchMedia(query).matches); +const useMedia = (query: string, defaultState: boolean = false) => { + const [state, setState] = useState(isClient ? () => window.matchMedia(query).matches : defaultState); useEffect(() => { let mounted = true; From d2de3d82f47e838ac9896775844d83b959f08c6b Mon Sep 17 00:00:00 2001 From: Ward Oosterlijnck Date: Tue, 16 Jul 2019 19:08:01 +1000 Subject: [PATCH 2/2] Update useMedia docs --- docs/useMedia.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/useMedia.md b/docs/useMedia.md index 4503e7e3bf..1c99c442ab 100644 --- a/docs/useMedia.md +++ b/docs/useMedia.md @@ -2,7 +2,6 @@ React sensor hook that tracks state of a CSS media query. - ## Usage ```jsx @@ -18,3 +17,11 @@ const Demo = () => { ); }; ``` + +## Reference + +```ts +useMedia(query: string, defaultState: boolean = false): boolean; +``` + +The `defaultState` parameter is only used as a fallback for server side rendering.