react-use icon indicating copy to clipboard operation
react-use copied to clipboard

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

Open christianschmitz opened this issue 1 year ago • 1 comments

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.

christianschmitz avatar Feb 10 '24 06:02 christianschmitz

https://github.com/streamich/react-use/pull/2543

geanify avatar Feb 19 '24 15:02 geanify

+1+1+1 image

clovu avatar May 22 '24 09:05 clovu

@geanify Good solution, thanks! Will close this.

christianschmitz avatar May 23 '24 17:05 christianschmitz