useMediaQuery in Next.js produces "Warning: Expected server HTML to contain a matching <div> in <div>."
ldrick opened this issue · 3 comments
Describe the bug
If you use in a Next.js Application useMedaQuery
it results in the same issue described here:
vercel/next.js#17443
To Reproduce
Steps to reproduce the behavior:
- Use Next.js Application and implement
useMedaQuery
in one Component - Load the dev environment of that Application
- Open Browser Console ( any current Firefox or CHrome will do)
- Press F5 in Browser to reload
- See error in console
Expected behavior
No error is thrown, as it further breaks reloading CSS in Next.js Dev Application and probably more.
Additional context
Following this amazing description: https://dev.to/adrien/creating-a-custom-react-hook-to-get-the-window-s-dimensions-in-next-js-135k it works for me like this right now:
import { useEffect, useState } from 'react';
const useMediaQuery = (mediaQuery: string): boolean => {
const [isVerified, setIsVerified] = useState(false);
useEffect(() => {
const mediaQueryList = window.matchMedia(mediaQuery);
const documentChangeHandler = (): void => setIsVerified(!!mediaQueryList.matches);
try {
mediaQueryList.addEventListener('change', documentChangeHandler);
} catch (e) {
// Safari isn't supporting mediaQueryList.addEventListener
mediaQueryList.addListener(documentChangeHandler);
}
documentChangeHandler();
return (): void => {
try {
mediaQueryList.removeEventListener('change', documentChangeHandler);
} catch (e) {
// Safari isn't supporting mediaQueryList.removeEventListener
mediaQueryList.removeListener(documentChangeHandler);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Empty array ensures that effect is only run on mount
return isVerified;
};
export { useMediaQuery };
Hi @ldrick sorry for the very late reply
I think you're right, that's a bug... would you mind to open a PR?
Does this error still occur for you? Because I've tested this on my app with next.js version 12.1.6 and I can't reproduce this.
I recently tested this on Next.js and same as Pawel I haven't got any error/message...
I'm closing this for now, thanks guys