How to listen to localstorage value changes in react?

The current answers are overlooking a really simple and secure option: window.dispatchEvent.

Where you set your localStorage item, if you dispatch an event at the same time then the eventListener in the same browser tab (no need to open another or mess with state) will also pick it up:

const handleLocalStorage = () => {
    window.localStorage.setItem("isThisInLocalStorage", "true");
    window.dispatchEvent(new Event("storage"));
};
window.addEventListener('storage', () => {
    console.log("Change to local storage!");
    // ...
})

EDIT:

Because this seems to be helpful, I’d also recommended checking out the useLocalStorage hook from the usehooks-ts team. You don’t need to install it as a package; you can just copy the hook wholesale. This hook makes use of the solution I originally shared, but adds a whole lot more sophisticated logic to it.

Leave a Comment