Q1. Why do we need cleanup in useEffect?
Cleanup is necessary to avoid memory leaks and unwanted behavior. For example, when you set up a subscription or event listener, you must remove it when the component unmounts or before the effect runs again. The cleanup function handles this.
Q2. How do you implement cleanup in useEffect?
Return a function from the effect. React will call this function before the component unmounts and before re-running the effect due to dependency changes. Example: useEffect(() => { const timer = setInterval(...); return () => clearInterval(timer); }, []);
Q3. When does the cleanup function run?
It runs before the component unmounts, and also before each re-execution of the effect (except the first run). This ensures that any previous side effects are cleaned up before setting up new ones.
Q4. Give an example where cleanup is essential.
If you add a window resize event listener in useEffect without cleanup, each re-render could add a new listener, causing multiple handlers. The cleanup removes the old listener before adding a new one, ensuring only one is active.
Q5. What happens if you don't clean up subscriptions?
Not cleaning up can lead to memory leaks, where the component is unmounted but subscriptions remain, causing state updates on unmounted components (React warnings) and wasted resources. Always clean up to prevent these issues.
