Cleanup Functions in React useEffect

When working with React’s useEffect hook we can add what’s called a “cleanup function”. This function is used to cancel any side effects that no longer require execution, before the component is unmounted.

Why are cleanup functions useful?

Using a cleanup function inside useEffect helps to prevent memory leaks or other errors when a side effect attempts to update a component that has already been unmounted. When these errors occur you’ll see them logged in the error console with a message like Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Basic Syntax

The basic syntax of a useEffect with a cleanup function looks like this:

useEffect(() => {
  // Do the effect here
  return () => {
    // Do the cleanup here
  }
}, [])

Example Usage

Clean up a setTimeout

In useEffect functions where we’ve added a setTimeout call, we can clean up after this by using the built-in clearTimeout function:

useEffect(() => {
  let example = setTimeout(() => {
    // Do the effect here   
  }, 1000);
  
  return () =>  {
    clearTimeout(example);
  };
}, []);

You can use the same approach with setInterval and clearInterval.

Clean up event listeners

When using addEventListener in a useEffect function, we can clean up after this by returning a removeEventListener function:

useEffect(() => {
  const examplePasteListener = () => {
    // Do some effect on the paste action
  };
  
  window.addEventListener('paste', examplePasteListener);
  
  return () => {
    window.removeEventListener('paste', examplePasteListener);
  };
}, []);
the author profile picture

Ryan Neilson is a software developer from Nova Scotia, Canada, where he lives with his wife and their menagerie of pets. He has worked extensively with PHP, WordPress, JavaScript, React, SCSS and CSS. Ryan can be found professionally at News Corp, where he works as a lead software engineer.