-
Notifications
You must be signed in to change notification settings - Fork 98
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
[useMediaQuery] React hydration doesn't re-evaluate the hook #163
Comments
This is always going to be a problem with SSR hydration. I am hesitant to add any logic to the hook to support this, because it encourages the anti-pattern of using JavaScript to change layout instead of CSS in situations where things are clearly being rendered outside of the |
I had the same issue with My workaround:
import { useState, useEffect } from "react";
export function useSsrCompatible<T>(newValue: T, initialValue: T) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
setValue(newValue);
}, [newValue]);
return value;
} Then use it like this: - const [ width, height ] = useWindowSize();
+ const [ width, height ] = useSsrCompatible(useWindowSize(), [0,0]); which makes Next.js' SSR happy. Definitely not ideal and makes sense not to include in the library. Although others may find this useful when needing to accomplish this, so glad there is an issue to track the question. |
That's very good! I like it a lot. |
Describe the bug
Next.JS does SSR and this hook sends a
false
first and then React doesn't update when it client-side detects atrue
. I made a work-around that makes it work. I am not sure what what internals make this problem occur.To Reproduce
I return different HTML depending on whether
isDesktop
is true or false and it seems like React assumes that that the HTML it got from the server was withisDesktop = true
while it was whenisDesktop = false
. For things like this I have always made auseEffect
to change the value and notuseState(theCurrentValue)
which would cause a discrepancy between server and browser.Expected behavior
Correctly rendered HTML.
Here is my work-around that makes this work regardless:
The text was updated successfully, but these errors were encountered: