useSessionStorageValue same key, different value
Prior Issues
I cannot see any related issues.
What is the current behavior?
Different instances of useSessionStorageValue with the same key that are mounted at the same can get out of sync when setValue is use on first mount within a useEffect. Only the component making the setValue call, and components before it, get the updated value. Components after do not update and have a stale value.
Steps to Reproduce
Using setValue in a useEffect(..., []).
const useStoredValue = () =>
useSessionStorageValue("example-key", "Default Value");
const UpdateOnMount = () => {
const [, setValue] = useStoredValue();
useEffect(() => {
setValue("Update Value");
}, [setValue]);
return null;
};
const DisplayValue = () => {
const [value] = useStoredValue();
return <p>Stored value is "{value}"</p>;
}
const App = () => (
<div>
<DisplayValue />
<UpdateOnMount />
<DisplayValue />
</div>
)
codesandbox: https://codesandbox.io/s/eager-gould-ter7m?file=/src/App.js
The code above on first load displays:
Stored value is "Update Value"
Stored value is "Default Value"
Another codesandbox with random values and reset buttons: https://codesandbox.io/s/fervent-stitch-zqekk
There's a few work arounds:
- Changing the component order
- Using
initializeWithStorageValue: false - Putting setValue in a setTimeout
useEffect(() => {
setTimeout(() => {
setValue("Update Value");
}, 0);
}, [setValue]);
What is the expected behavior?
All instances of useSessionStorageValue with the same key should return the same value.
Environment Details
-
@react-hookz/webversion: 12.0.0 -
reactversion: 17.0.2 -
react-domversion: 17.0.2 -
typescriptversion: N/A - OS: macOS BigSur
- Browser: Chrome 95 / Firefox / Safari
- Did this work in previous versions? No know
:tada: This issue has been resolved in version 12.0.3 :tada:
The release is available on:
Your semantic-release bot :package::rocket:
Well, nope, didnt worked out. Ill dig more later.
I'm investigating this also. Will report here if I find anything out.
I can confirm that:
- This affects both
useLocalStorageanduseSessionStorage(which is not surprising, since both useuseStorageunder the hood). - This bug has been present since
useLocalStorageanduseSessionStoragewere first added to this library.
:tada: This issue has been resolved in version 17.0.0 :tada:
The release is available on:
Your semantic-release bot :package::rocket: