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.