Skip to content

Commit 8762f90

Browse files
authored
Merge pull request #948 from wereHamster/fix-924
useBreakpointIndex: Do not depend on window during setState initialization
2 parents 4ff2eb1 + 3d84859 commit 8762f90

File tree

1 file changed

+19
-24
lines changed

1 file changed

+19
-24
lines changed

packages/match-media/src/index.ts

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,39 +12,34 @@ export const useBreakpointIndex = (options: defaultOptions = {}) => {
1212
const breakpoints =
1313
(context.theme && context.theme.breakpoints) || defaultBreakpoints
1414

15-
const getIndex = useCallback(() => {
16-
if (typeof window === 'undefined') {
17-
if (typeof defaultIndex === 'number') {
18-
if (defaultIndex < 0 || defaultIndex > breakpoints.length - 1) {
19-
throw new RangeError(
20-
`Default breakpoint index out of range. Theme has ${breakpoints.length} breakpoints, got index ${defaultIndex}`
21-
)
22-
}
23-
return defaultIndex
24-
}
25-
throw new TypeError(
26-
`Default breakpoint index should be a number. Got: ${defaultIndex}, ${typeof defaultIndex}`
27-
)
28-
}
29-
30-
return breakpoints.filter(
31-
breakpoint =>
32-
window.matchMedia(`screen and (min-width: ${breakpoint})`).matches
33-
).length
34-
}, [breakpoints, defaultIndex])
35-
36-
const [value, setValue] = useState(getIndex)
37-
15+
if (typeof defaultIndex !== 'number') {
16+
throw new TypeError(
17+
`Default breakpoint index should be a number. Got: ${defaultIndex}, ${typeof defaultIndex}`
18+
)
19+
} else if (defaultIndex < 0 || defaultIndex > breakpoints.length - 1) {
20+
throw new RangeError(
21+
`Default breakpoint index out of range. Theme has ${breakpoints.length} breakpoints, got index ${defaultIndex}`
22+
)
23+
}
24+
25+
const [value, setValue] = useState(defaultIndex)
3826
useEffect(() => {
27+
const getIndex = () =>
28+
breakpoints.filter(
29+
(bp) => window.matchMedia(`screen and (min-width: ${bp})`).matches
30+
).length
31+
3932
const onResize = () => {
4033
const newValue = getIndex()
4134
if (value !== newValue) {
4235
setValue(newValue)
4336
}
4437
}
38+
39+
onResize()
4540
window.addEventListener('resize', onResize)
4641
return () => window.removeEventListener('resize', onResize)
47-
}, [breakpoints, getIndex, value])
42+
}, [breakpoints, value])
4843

4944
return value
5045
}

0 commit comments

Comments
 (0)