skip to Main Content

I have some React components and they use localstorage to store some information.
These are tied to state variables with a custom hook:

export const useLocalStorage = (key, defaultValue) => {
    const [value, setValue] = useState(() => {
        return getStorageValue(key, defaultValue);
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

The component uses this like:

const [thing, setThing] = useLocalStorage('thing', '');

Now, what I want, is to clear this when the component unmounts.

I have tried to clear this with useEffect:

useEffect(() => {
    return () => {
        setThing(prevThing => '');
    }
},[]);

However, this doesn’t seem to work. I can even console log in the cleanup
function and see that, but the state change and subsequent clearing of the
localstorage doesn’t happen. I’m unsure how to get this to properly clear.

Edit (adding getStorageValue):

const getStorageValue = (key, defaultValue) => {
    let value;
    try {
        const saved = localStorage.getItem(key);
        value = JSON.parse(saved);

    } catch(err) {
        value = false;
    }

    return value || defaultValue;
}

2

Answers


  1. React component’s local state won’t know anything about the localStorage. If your hook is setting something to local storage, then it’s the job of the hook to clear it on unmount if needed.

    It won’t happen automatically.

    Login or Signup to reply.
  2. If I understand correctly you tried to set the value to "" expecting the useEffect callback to run in response and set the localStorage item to "". However, setting the value is a no-op because the component is already unmounting. You should see a warning in the console when this happens.

    Luckily you can still access localStorage from a cleanup callback as that doesn’t depend on the component.

    useEffect(() => {
        return () => {
            localStorage.setItem(key, '');
        }
    }, [key]);
    

    This hook invocation will set the item to "" when key changes or the component is unmounted.


    As an aside, Storage.setItem(key, '') does not unset the key but rather sets an empty string as its value. To unset a key, use Storage.removeItem(key).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search