Description
Describe the bug
When using either the useSessionStorage or useLocalStorage, they don't have the same initialValue between the one in the setValue callback and what's returned by the hook.
This means that if how the initialStorage is calculated changes mid execution, both values would not align and breaks some behaviors.
It only happens at the first execution of the setValue
function.
To Reproduce
Take this code as example:
let someVariable = 0;
const [value, setValue] = useSessionStorage('key', () => someVariable + 1);
We can see that the initialValue is being calculated adding 1 to someVariable
. This would say that the initialValue is 1, and value
in the example above is actually equal to 1.
Then if I modify someVariable
to 2 for example, and then call setValue
, the param of the callback of setValue, will be equal to 3 and not 1 as the initialValue was. And value
is still equal to 1.
This is because when calling setValue((oldValue) => oldValue + 1)
, as nothing is stored in the browser sessionStorage, it will go get the initialValue and execute the function again. Which will be 3 as someVariable
is now equal to 2.
Small excalidraw to explain the timeline of the events
Expected behavior
The expected behavior would be that instead of going to get the initialValue when calling the setValue
for the first time, it would use the storedValue
state.
Small excalidraw to explain the timeline of the events
This would ensure that:
- The value returned by the hook is the same used in the callback of setValue.
- If the elements that compose the initialValue changes, it will not affect the behavior of this hook.
- Align it to work the same way as
useState
does, which even if the initialValue changes, it doesn't care.
Additional context
If this is an expected behavior, it should be explicitly mentioned in the docs, as it's easy to suppose it would work as the native useState
but with the addition that it also stores it in a persistent storage.
Feel free to ask for more information if it's not very clear above.
Let me know if the requested changes make sense, and I can open a PR to do contribute either to the code or the documentation.