When should I return a cleanup function?
Whenever the effect sets up something that needs tearing down: a subscription, timer, event listener, or fetch. A good rule is to ask what tears down what you set up; if the answer is nothing, you have a leak.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Clean Up Side Effects in React useEffect
It is the function you return from useEffect. React calls it before the next effect runs and when the component unmounts. It is where you tear down whatever the effect set up, like subscriptions and timers.
Because if you set up a subscription, timer, or listener and never remove it, it keeps running after the component unmounts. This leaks memory and tries to update state on an unmounted component, causing warnings and bugs.
Subscribe in the effect and return a function that unsubscribes. React calls that function before the next effect and on unmount, so the subscription is always removed when it is no longer needed.
Still have questions?
Browse all our FAQs or reach out to our support team
