The unmounting phase is when a React component is removed from the screen. It helps clean up things like timers or event listeners so the app stays fast and bug-free.
Unmounting phase in React
useEffect(() => {
// setup code here
return () => {
// cleanup code here runs on unmount
};
}, []);The cleanup function inside useEffect runs when the component unmounts.
Passing an empty array [] as the second argument means the effect runs once and cleans up on unmount.
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timer);
};
}, []);useEffect(() => {
function onResize() {
console.log('Window resized');
}
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, []);This component shows seconds passed, increasing every second. When the component is removed, the timer stops and logs a message.
import React, { useState, useEffect } from 'react'; function Timer() { const [count, setCount] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setCount(c => c + 1); }, 1000); return () => { clearInterval(intervalId); console.log('Timer stopped'); }; }, []); return ( <div> <p>Seconds passed: {count}</p> </div> ); } export default Timer;
Always clean up timers, listeners, or subscriptions in the unmount phase to keep your app smooth.
Without cleanup, your app might slow down or behave strangely over time.
The unmounting phase lets you clean up before a component disappears.
Use the cleanup function inside useEffect to stop timers or remove listeners.
This keeps your app fast and prevents bugs.
Practice
Solution
Step 1: Understand the unmounting phase
The unmounting phase happens when a component is about to be removed from the screen.Step 2: Identify the purpose of cleanup
During unmounting, React lets you clean up things like timers or event listeners to avoid bugs and memory leaks.Final Answer:
To clean up resources like timers or event listeners before the component is removed -> Option DQuick Check:
Unmounting phase = cleanup before removal [OK]
- Confusing unmounting with mounting or updating phases
- Thinking unmounting initializes state
- Believing unmounting is for rendering UI
useEffect hook?Solution
Step 1: Recall useEffect cleanup syntax
The cleanup function must be returned from the function passed to useEffect.Step 2: Check each option's syntax
useEffect(() => { return () => { clearTimeout(timer); }; }, []); correctly returns a function that calls clearTimeout. Others either call clearTimeout immediately or do not return a function.Final Answer:
useEffect(() => { return () => { clearTimeout(timer); }; }, []); -> Option AQuick Check:
Cleanup function is returned inside useEffect [OK]
- Calling cleanup directly instead of returning a function
- Not returning anything from useEffect
- Returning the cleanup call instead of a function
import React, { useEffect } from 'react';
function Timer() {
useEffect(() => {
const id = setInterval(() => console.log('Tick'), 1000);
return () => {
clearInterval(id);
console.log('Cleanup');
};
}, []);
return <div>Timer running</div>;
}Solution
Step 1: Understand the effect and cleanup
The effect sets an interval that logs 'Tick' every second. The cleanup clears the interval and logs 'Cleanup'.Step 2: What happens on unmount?
When the component unmounts, the cleanup runs once, clearing the interval and logging 'Cleanup'. No more 'Tick' logs happen after unmount.Final Answer:
'Cleanup' logged once on unmount -> Option CQuick Check:
Cleanup logs once on unmount [OK]
- Thinking 'Tick' logs after unmount
- Expecting no logs on unmount
- Confusing cleanup timing with effect start
import React, { useEffect } from 'react';
function Listener() {
useEffect(() => {
window.addEventListener('resize', () => console.log('Resized'));
}, []);
return <div>Listening</div>;
}Solution
Step 1: Check event listener setup
The component adds a resize event listener on mount but does not remove it on unmount.Step 2: Identify missing cleanup
Without cleanup, the listener stays active after unmount, causing memory leaks or bugs.Final Answer:
Missing cleanup function to remove the event listener on unmount -> Option BQuick Check:
Always remove listeners in cleanup [OK]
- Forgetting to remove event listeners on unmount
- Thinking arrow functions can't be event callbacks
- Misusing dependency arrays in useEffect
useEffect. Which is the best way to ensure the connection closes properly when the component unmounts?useEffect(() => {
const socket = new WebSocket('wss://example.com');
socket.onmessage = (event) => console.log(event.data);
// What should go here?
}, []);Solution
Step 1: Understand WebSocket lifecycle in React
WebSocket connections stay open until explicitly closed. They do not close automatically on component unmount.Step 2: Implement cleanup to close connection
Returning a cleanup function that callssocket.close()ensures the connection closes when the component unmounts, preventing resource leaks.Final Answer:
Return a cleanup function that callssocket.close()to close the connection -> Option AQuick Check:
Close WebSocket in cleanup function [OK]
- Closing WebSocket immediately instead of on unmount
- Assuming WebSocket closes automatically
- Setting socket to null without closing
Ready to prove it?
Pass the test and this pattern moves unknown
