When should I return a cleanup function from useEffect?
Whenever the effect sets up something that needs tearing down, like a subscription, event listener, or timer. Return a cleanup function so React can remove it before the next effect and on unmount, preventing memory leaks and stale updates.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in What Is useEffect in React and How Does It Work?
useEffect runs a function after the component renders to perform side effects like data fetching, subscriptions, and DOM manipulation. It can optionally return a cleanup function that runs before the next effect or on unmount.
It controls when the effect runs. No array means it runs after every render. An empty array means it runs only on mount. An array with values means it runs when any of those values change.
Usually because you forgot the dependency array, or because you included a state variable that you update inside the effect. Each update triggers another run. Fix the dependency array so the effect only runs when intended.
Still have questions?
Browse all our FAQs or reach out to our support team
