Skip to content

useLocalStorage: initialValue should not update the stored value after its first use #177

@k35o

Description

@k35o

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions