Skip to content

Commit 46e5bcc

Browse files
authored
fix(useMediaQuery): On misconfiguration, cause hydration error instead of SSR crash (#1042)
In #1000 it was noted, that the current implementation does not follow the convention of causing a hydration error on misconfiguration. This is now fixed. re #1000
1 parent 7358f1e commit 46e5bcc

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/useMediaQuery/useMediaQuery.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Dispatch, useEffect, useState } from 'react';
2+
import { isBrowser } from '../util/const';
23

34
const queriesMap = new Map<
45
string,
@@ -66,9 +67,18 @@ interface UseMediaQueryOptions {
6667
* `initializeWithValue` (default: `true`) - Determine media query match state on first render. Setting
6768
* this to false will make the hook yield `undefined` on first render.
6869
*/
69-
export function useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean | undefined {
70+
export function useMediaQuery(
71+
query: string,
72+
options: UseMediaQueryOptions = {}
73+
): boolean | undefined {
74+
let { initializeWithValue = true } = options;
75+
76+
if (!isBrowser) {
77+
initializeWithValue = false;
78+
}
79+
7080
const [state, setState] = useState<boolean | undefined>(() => {
71-
if (options?.initializeWithValue ?? true) {
81+
if (initializeWithValue) {
7282
let entry = queriesMap.get(query);
7383
if (!entry) {
7484
entry = createQueryEntry(query);

0 commit comments

Comments
 (0)