Skip to content
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

[BUG] useLocalStorage Hydration Mismatch — Need to setIsClient everywhere #644

Open
anaclumos opened this issue Oct 15, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@anaclumos
Copy link

Describe the bug

In Next.js 15 App Router React Server Components, setting something on the client side (different from the default value) causes a hydration error. Theoretically, I could've useEffect setIsClient(true) everywhere, but that's tedious, and I thought it should be handled at the library level.

To Reproduce

https://stackblitz.com/edit/stackblitz-starters-ty7dbs

Screen.Recording.2024-10-15.at.9.45.24.AM.mov

Expected behavior

It should "re-render" and not cause a hydration error

Additional context

Just started sponsoring you. Great work!

@anaclumos anaclumos added the bug Something isn't working label Oct 15, 2024
@adevinwild
Copy link

adevinwild commented Nov 19, 2024

Hey @anaclumos
Had the same issue on my side, you can fix the hydration error by using the options on the hook :

// ❌ This will throw an error
const myValue = useReadLocalStorage('my_value')

// ✅ This will work out of the box for SSR / RSC
const myValue = useReadLocalStorage('my_value', { initializeWithValue : false })

A quick description about it that I've found on the docs :

If true (default), the hook will initialize reading the local storage. In SSR, you should set it to false, returning undefined initially.

For more reference, check the docs "here"
Of course it also works for the useLocalStorage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants