-
-
Notifications
You must be signed in to change notification settings - Fork 17
Open
Description
Currently, the useLocalStorage hook updates the value in localStorage if its initialValue prop changes after the hook has been initialized.
useEffect(() => {
if (
getLocalStorageItem(key) === null &&
typeof initialValue !== "undefined"
) {
setLocalStorageItem(key, initialValue);
}
}, [key, initialValue]);This behavior differs from React's standard useState hook. With useState, if the initialState argument provided to it changes during subsequent re-renders, the existing state is not updated to this new initialState. The initial state is only used when the state is first created.
To align useLocalStorage more closely with React's standard API patterns and make its behavior more predictable for developers, I propose that changes to the initialValue prop should not update an already existing value in localStorage.
// first render
const { current } = useLocalStorage(key1, 'hello');
console.log(current); // hello;
// next render
const { current } = useLocalStorage(key1, 'world');
console.log(current); // expect 'hello', not 'world'
// next render 2
const { current } = useLocalStorage(key2, 'world');
console.log(current); // 'world'Thank you for considering this proposal.
Metadata
Metadata
Assignees
Labels
No labels