streamich / react-use

React Hooks — 👍
http://streamich.github.io/react-use
The Unlicense
41.98k stars 3.16k forks source link

useSessionStorage is tied up to a component state and not to SS #2597

Open rizametovd opened 1 month ago

rizametovd commented 1 month ago

What is the current behavior?

I have an object with the following signature:

type Value = {
    a: string[],
    b: string[]
}

And the two components ComponenA and ComponentB and SS key myKey. Whenever user clicks on ComponentA value.a should be updated in SS and value.b should not be overridden. Actually useSessionStorage overrides the SS value depending on which component was clicked last. For example user cliked several times on both components, the SS value is:

  {
    b: ["Value B", "Value B", "Value B", "Value B"],
  };

CodeSanbox

What is the expected behavior? The SS should be updated for the myKey. Say user clicked several times on both components then SS value should look something like:

 {
    a: ["Value A", "Value A", "Value A", "Value A"],
    b: ["Value B", "Value B"],
  };

A little about versions:

OmriHab commented 1 month ago

The state is saved locally in the hook itself. On each state update the SS itself is updated, but the default value is read from the session storage once on the initial render of the component that is using the hook. So if one component updates its state, and by side-effect the SS, the other component won't get the new value.

The ways I can think to fix this is either for the hook to listen to the SS or a custom event fired on the SS update, or to keep the state in a app-wide context. I'm new to this library so I'm not sure if this is outside the scope of the complexity of this lib, it might be best to leave it with this behavior and add it to the documentation.

I'd be glad to get the feedback of the maintainer and create a PR to fix it.