removeEventListener for window.onstorage?

1.6k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

When you add a listener like

window.onstorage = () => { ... }

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 to addEventListener to be passed on to removeEventListener

You can clean it up by setting the storage listener function to null

useEffect(() => {
    // other code
    return () => { window.onstorage = null };
}, []);