Skip to content

Commit 24413b7

Browse files
committed
fix(devtools): guard against window in useMediaQuery
Fixes TanStack#1515
1 parent c95cebc commit 24413b7

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

src/devtools/useMediaQuery.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,32 @@ import React from 'react'
44

55
export default function useMediaQuery(query) {
66
// Keep track of the preference in state, start with the current match
7-
const [isMatch, setIsMatch] = React.useState(
8-
() => window.matchMedia && window.matchMedia(query).matches
9-
)
7+
const [isMatch, setIsMatch] = React.useState(() => {
8+
if (typeof window !== 'undefined') {
9+
return window.matchMedia && window.matchMedia(query).matches
10+
}
11+
})
1012

1113
// Watch for changes
1214
React.useEffect(() => {
13-
if (!window.matchMedia) {
14-
return
15-
}
15+
if (typeof window !== 'undefined') {
16+
if (!window.matchMedia) {
17+
return
18+
}
1619

17-
// Create a matcher
18-
const matcher = window.matchMedia(query)
20+
// Create a matcher
21+
const matcher = window.matchMedia(query)
1922

20-
// Create our handler
21-
const onChange = ({ matches }) => setIsMatch(matches)
23+
// Create our handler
24+
const onChange = ({ matches }) => setIsMatch(matches)
2225

23-
// Listen for changes
24-
matcher.addListener(onChange)
26+
// Listen for changes
27+
matcher.addListener(onChange)
2528

26-
return () => {
27-
// Stop listening for changes
28-
matcher.removeListener(onChange)
29+
return () => {
30+
// Stop listening for changes
31+
matcher.removeListener(onChange)
32+
}
2933
}
3034
}, [isMatch, query, setIsMatch])
3135

0 commit comments

Comments
 (0)