react-use: useLocalStorage mismatches server render
Any server rendering solution won’t have access to a browser’s local storage, so it will default to the initialValue. Since useLocalStorage will use the actual local storage value on first render, this will immediately end up in a react hydration mismatch anytime the local storage value is not equal to the initialValue.
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 9
- Comments: 15 (4 by maintainers)
You can also try disabling SSR for the component that is using local storage state.
In Next.js, for instance, you could do this:
https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
I use useLocalStorage in nextjs 13, and it still throws error
Quick update: SSR is now fully supported by the
useLocalStorageValueanduseSessionStorageValuehooks included in@react-hookz/web! For reference, here are the docs on useLocalStorageValue and useSessionStorageValue.If you are thinking of migrating, we have created a handy react-use to @react-hookz/web migration guide. Hope it helps!
@dlbnco that’s one way to solve it. What I’m claiming is that the hook’s issue can be isolated to the hook, rather than requiring the entire component be blocked out via SSR. This lets the implementer decide how they want to handle the situation where the value isn’t loaded on the frontend rather than the blanket solution where they don’t show the component, since the component itself has no issues showing.
Maybe we can add an option, if true, that would on the browser return the default value first, and only then re-render with a real value?