What is the cleanup function in useEffect, and when does it run?

React hooks and effects · Freshers

Model answer

Return a function from the effect to undo what it set up: clearInterval, removeEventListener, unsubscribe, or abort a request. React calls it before re-running the effect because dependencies changed, and when the component unmounts.

Without cleanup you get memory leaks, duplicate listeners, and updates from stale requests.

Learn this topic

React useEffect Explained: Side Effects, Dependencies and Cleanup in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions