'can't detect window width using hook
I am using Gatsby and react-hook/media-query to detect window width changes.
I think it works fine in most cases, but I notify that it doesn't work in weird way.
Here's my custom hook for all media queries.
import { useMediaQueries } from '@react-hook/media-query';
export default function useDetectDevice() {
const { matchesAll: isMobile } = useMediaQueries({
screen: 'screen',
width: '(max-width: 640px)'
});
...
return {
isMobile,
...
};
}
const NewPage = () => {
const { isMobile } = useDetectDevice();
return (
<h1 style={{isMobile ? '2.25rem' : '6rem'}}>test<h1>
);
}
This works if I change window width through chrome or any web browser, but doesn't work if I fresh start the page.
How can I fix this issue?
Solution 1:[1]
It seems that the SSR is breaking the initial calculations. Try adding the typeof window != 'undefined'
condition or delay a little bit the initial calculation using a useEffect
hook like:
import { useMediaQueries } from '@react-hook/media-query';
export default function useDetectDevice() {
if (typeof window != 'undefined'){
const { matchesAll: isMobile } = useMediaQueries({
screen: 'screen',
width: '(max-width: 640px)'
});
...
return {
isMobile,
...
};
}
}
Of course, tweak the snippet to make it work but get the idea (defining an empty variable and filling it inside the condition or similar).
As I said, alternatively, you can use the useLayoutEffect
or the useEffect
(with empty deps, []
) hook to trigger the calculations to ensure that the DOM tree is already loaded.
Related issues:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |