Categories
React Answers

How to instantly update state when any changes into the localStorage in React?

Spread the love

To instantly update state when any changes into the localStorage in React, we listen to the storage event.

For instance, in our component, we write

React.useEffect(() => {
  window.addEventListener("storage", () => {
    setCart(JSON.parse(localStorage.getItem("myCart")) || []);
  });
}, []);

to add the storage event listener with window.addEventListener in the useEffect callback.

Then we call setCart when local storage changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *