How do you properly clean up event listeners to avoid memory leaks?
Short answer
Call removeEventListener() with the exact same function reference and options used in addEventListener() — anonymous inline functions can't be removed this way, so store a named reference if you'll need to detach it later.
Advertisement
AModel answer
Call removeEventListener() with the exact same function reference and options used in addEventListener() — anonymous inline functions can't be removed this way, so store a named reference if you'll need to detach it later.
function handleClick() { console.log('clicked'); }
el.addEventListener('click', handleClick);
// later:
el.removeEventListener('click', handleClick);Real-world example
Removing listeners in a React useEffect cleanup function or when a component/widget is destroyed.
Likely follow-ups
- Why do arrow functions defined inline in addEventListener() cause a common removeEventListener bug?
Related topics