Skip to content

Commit

Permalink
fix(useMediaQuery): On misconfiguration, cause hydration error instea…
Browse files Browse the repository at this point in the history
…d 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
  • Loading branch information
ArttuOll authored Dec 7, 2022
1 parent 7358f1e commit 46e5bcc
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/useMediaQuery/useMediaQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Dispatch, useEffect, useState } from 'react';
import { isBrowser } from '../util/const';

const queriesMap = new Map<
string,
Expand Down Expand Up @@ -66,9 +67,18 @@ interface UseMediaQueryOptions {
* `initializeWithValue` (default: `true`) - Determine media query match state on first render. Setting
* this to false will make the hook yield `undefined` on first render.
*/
export function useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean | undefined {
export function useMediaQuery(
query: string,
options: UseMediaQueryOptions = {}
): boolean | undefined {
let { initializeWithValue = true } = options;

if (!isBrowser) {
initializeWithValue = false;
}

const [state, setState] = useState<boolean | undefined>(() => {
if (options?.initializeWithValue ?? true) {
if (initializeWithValue) {
let entry = queriesMap.get(query);
if (!entry) {
entry = createQueryEntry(query);
Expand Down

0 comments on commit 46e5bcc

Please sign in to comment.