New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
NextJS & SSR Bug: Warning: Prop className did not match on useMediaQuery #4319
Comments
Hi @niconiahi, As mentioned in the docs,
To fix this, I recommend waiting for the client to be re-hydrated by using a const [mounted, setMounted] = useState(false)
const value = useMediaquery(...)
useEffect(()=>{
setMounted(true)
},[])
return mounted ? value : null Be sure to add a spinner or skeleton to that portion of the page so there's no layout shift. |
@segunadebayo maybe we should include your suggestion implementation in doc or inside the Or you consider it might mislead some people how to use it without specific concern. |
So there is a mismatch in the className between server and client, and the solution is to add a spinner and set the value with useEffect to fix a media query? Maybe it's me, but that doesn't sound right. |
It seems not working when I do it with remix.. |
The idea of this code is to avoid rendering the hook This particular hook is client side only. That's why I asked to include the implementation in doc, instead of using one line of text to mention it doesn't work in server side rendering. But depending on the readers' background knowledge, this also might not immediately obvious for them. |
In my project I came up with a hook that can wrap the value that leads to a server-client mismatch: export const useClientSideValue = <T>(value: T, ssrValue: T): T => {
// Needed to prevent a mismatch between the first render on the server and the client
const [mountedValue, setMountedValue] = useState(ssrValue);
useEffect(() => setMountedValue(value), [value]);
return mountedValue;
}; Usage: const clientValue = useMediaquery(...);
const value = useClientSideValue(clientValue, ''); |
Description
On a NextJS application, when using Chakra's useMediaQuery to determine a value for a Text prop, it prints an error about a non matching className on the server and the client
Link to Reproduction
https://codesandbox.io/s/festive-keller-6jhy5
Steps to reproduce
IN THE SANDBOX WORKS:
IN MY NEXTJS APP WITH CHAKRA DOES NOT.
Am I missing something?
Code reference (same as codesandbox but in real app)
same happening to me when ussing
useMediaQuery
as so:then used: (THIS THROWS AN ERROR)
used: (THIS DOESN'T)
screenshot here:
Chakra UI Version
1.6.4
Browser
Google Chrome 91.0.4472.114
Operating System
Additional Information
Relates to this issue:
#684
The text was updated successfully, but these errors were encountered: