Cleanup side effects on useEffect hooks

useEffect hooks help to run any side-effects in the code. But if you left the side-effects to run even after unmounting, then it will cause performance issues and memory leaks in the application.

How to avoid that?

useEffect has a return function to write your cleanup code.

useEffect(() => {
  // Code for side-effects

  return () => {
    // Code to cleanup the side-effects
}, []);

Some of the use cases can be,

  • Removing event listeners
  • Clearing timers (i.e., clearTimeout, clearInterval)
  • Aborting any unresolved ajax requests

We will see a simple example of clearing a timeout. The timer sets a state every 3 seconds. We will clean the timer when the component unmounts.

useEffect(() => {
  // Change name every 3 seconds here
  const timer = setTimeout(() => {
    const newName = name === 'Param' ? 'Joshua' : 'Param';
  }, 3000);

  // Cleanup side-effect
  return () => {
    // Clear timer
    console.log('timer cleared on unmounting process');
}, [name]);

This component unmounts and mounts again every 3 seconds due to the timer. It is just for learning purposes. In the ideal case, you can run this using setInterval and avoid unnecessary re-mounting.

Check it in action here,