How to Remove an Event listener in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Remove an Event listener in React #

To remove an event listener in React:

  1. Add the event listener in the useEffect hook.
  2. Return a function from the useEffect hook.
  3. Use the removeEventListener method to remove the event listener when the component unmounts.
App.js
import {useRef, useEffect} from 'react'; const App = () => { const ref = useRef(null); useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); // 👇️ remove the event listener when component unmounts return () => { element.removeEventListener('click', handleClick); }; }, []); return ( <div> <button ref={ref}>Click</button> </div> ); }; export default App;

We added an event listener to an element in the useEffect hook of the component.

If you want to add an event listener to the window, or document objects, use the same approach, excluding the ref.

We passed an empty dependencies array to the useEffect hook, so it's only going to run when the component mounts.

We only want to call the addEventListener method once - when the component mounts.

App.js
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []);

We stored the a reference to the element in a variable and used the addEventListener method to add a click event listener to the button.

The first parameter the method takes is the type of the event to listen for, and the second is a function that gets invoked when an event of the specified type occurs.

The function we returned from the useEffect hook is called when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

The 2 parameters we passed to the removeEventListener method are:

  1. The type of the event for which to remove the event listener.
  2. The corresponding event handler function.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.