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

useLocalStorage documentation: warn against calling with same key in multiple components #2540

Closed
christianschmitz opened this issue Feb 10, 2024 · 3 comments

Comments

@christianschmitz
Copy link

Is your feature request related to a problem? Please describe.
useLocalStorage internally keeps a copy of the stored value using useState, if this state is updated within one component the change won't be reflected in other components using the same hook with the same key.

Describe the solution you'd like
A short note in the docs describing that useLocalStorage should only be used in a single component instance for a given key. If used in multiple locations a custom version of useLocalStorage must be implemented that keeps its state in a global store (eg. redux).

I used this hook without thinking and spent 1-hour debugging strange behavior. The issue was obvious once I looked at the underlying code. Seems like an easy trap to fall into without a clear warning in the docs.

It could also be that useLocalStorage uses a trick I'm unaware of to mimic storing the state globally. In that case, I am probably using the hook incorrectly, and once I figure it out we can add a short description of what I'm doing wrong to the docs.

Describe alternatives you've considered
Deprecate/remove useLocalStorage from the react-use code base, but there are probably too many dependants.

@geanify
Copy link

geanify commented Feb 19, 2024

#2543

@clover-you
Copy link

+1+1+1
image

@christianschmitz
Copy link
Author

@geanify
Good solution, thanks! Will close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants