Sobes.tech
Middle

When does the cleanup function in useEffect trigger?

sobes.tech AI

Answer from AI

The cleanup function in useEffect runs in the following cases:

  • Before re-running the effect when dependencies change.
  • When the component unmounts.

This allows for proper resource cleanup, canceling subscriptions or timers to prevent memory leaks and incorrect behavior.

Example:

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

  return () => {
    clearInterval(id); // cleanup on unmount or update
  };
}, []); // empty dependency array — effect runs once
When does the cleanup function in useEffect trigger… - sobes.tech