Sobes.tech
Senior

What is a cleanup function in useEffect and when does it trigger?

sobes.tech AI

Answer from AI

In React, the useEffect hook can return a cleanup function, which is called to cancel side effects before the next effect runs or when the component unmounts.

It is needed to free resources, cancel subscriptions, timers, or other operations that could lead to memory leaks or undesirable behavior.

Example:

useEffect(() => {
  const id = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => {
    clearInterval(id); // Cleanup timer on unmount or update
  };
}, []);

In this example, the cleanup function clears the timer so it does not continue to run after the component has been removed from the DOM.