[BUG] Why useSessionStorage and useLocalStorage doesn't use the storedValue
state instead of recalculating the initialValue again?
#662
Labels
bug
Something isn't working
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:
We can see that the initialValue is being calculated adding 1 to
someVariable
. This would say that the initialValue is 1, andvalue
in the example above is actually equal to 1.Then if I modify
someVariable
to 2 for example, and then callsetValue
, the param of the callback of setValue, will be equal to 3 and not 1 as the initialValue was. Andvalue
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 assomeVariable
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 thestoredValue
state.Small excalidraw to explain the timeline of the events
This would ensure that:
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.
The text was updated successfully, but these errors were encountered: