Blog>
Snippets

Preventing Memory Leaks with Proper Event Listener Management

Provide code examples on how to properly add and remove event listeners to prevent memory leaks, including the use of named functions and the removal of listeners on component unmount.
function handleClick() {
    console.log('Button clicked');
}

document.getElementById('myButton').addEventListener('click', handleClick);

// Later, to prevent memory leaks, remove the event listener
document.getElementById('myButton').removeEventListener('click', handleClick);
This code snippet adds an event listener to an element with ID 'myButton'. The event listener executes the 'handleClick' function when a 'click' event occurs. To prevent memory leaks, especially when the element is removed or no longer needed, the event listener is also removed using 'removeEventListener' with the same function reference 'handleClick'.
// Assuming this is used within a component in a framework like React

class MyComponent extends React.Component {
    componentDidMount() {
        window.addEventListener('resize', this.handleResize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
    }

    handleResize = () => {
        // Handle the resize event
    };

    render() {
        // Render method logic here
    }
}
In a class-based React component, 'componentDidMount' is used to add an event listener for the 'resize' event when the component mounts. The 'handleResize' method is bound to the component instance and is used as the event handler. Before the component unmounts and is destroyed, 'componentWillUnmount' is used to remove the event listener to prevent potential memory leaks.
import React, { useEffect } from 'react';

function MyFunctionalComponent() {
    useEffect(() => {
        const handleScroll = () => {
            // Handle the scroll event
        };

        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);

    return (
        // Your component JSX goes here
    );
}
In this functional React component, the 'useEffect' hook is used to add an event listener for the 'scroll' event. Within the hook, a cleanup function is returned which removes the event listener. This pattern ensures that the event listener is cleaned up when the component unmounts, preventing memory leaks.