useMedia flashes wrong state
dreyks opened this issue · 0 comments
dreyks commented
defaultMatches
bleeds through the initial render resulting in flashes of wrong state. replacing useEffect
with useLayoutEffect
would fix this but would require a workaround for server-side rendering
alternatively something like this could work
const mediaQueryList = useRef()
const getMediaQueryList = () => window.matchMedia(
typeof query === 'string' ? query : json2mq(query)
);
let initialMatches;
if (typeof window !== 'undefined') {
mediaQueryList.current = getMediaQueryList();
initialMatches = mediaQueryList.current.matches;
}
initialMatches = typeof initialMatches !== 'undefined' ? initialMatches : defaultMatches;
const [matches, setMatches] = useState(initialMatches);
useEffect(
() => {
mediaQueryList.current = mediaQueryList.current || getMediaQueryList()
// the rest of the method
},
[query]
)
what do you think?