The MDN docs describe two possible ways to listen to storage events, window.addEventListener('storage', () => { ... })
and window.onstorage = () => { ... }
. In a React app, if I used addEventListener inside of a useEffect hook, I'd want to return the cleanup function window.removeEventListener('storage', ... )
to avoid a memory leak after the component unmounts.
However, window.onstorage = () => { ... }
does not offer a way to remove the event listener. Does this mean that it's safe to listen to storage events this way without returning a cleanup function in a useEffect hook?
When you add a listener like
You are technically allowed to only have one listener in your application on storage. However if
window.addEventListener
you can have as many event listeners as you want and cleanup requires the same function reference that was passed toaddEventListener
to be passed on toremoveEventListener
You can clean it up by setting the storage listener function to null