Bird
Raised Fist0
Reactframework~10 mins

Unmounting phase in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Unmounting phase
Component Mounted
↓
User triggers unmount
↓
React calls cleanup functions
↓
Component DOM removed
↓
Component fully unmounted
This flow shows how React removes a component: it first calls cleanup code, then removes the component from the page.
Execution Sample
React
import React, { useEffect } from 'react';

function Timer() {
  useEffect(() => {
    const id = setInterval(() => console.log('tick'), 1000);
    return () => clearInterval(id);
  }, []);
  return <div>Timer running</div>;
}
This component logs 'tick' every second and cleans up the timer when it unmounts.
Execution Table
StepTriggerState BeforeActionState AfterWhat Re-rendersDOM Change
1Component mountsNo timer runningSet interval timerTimer runningTimer componentTimer div added
2Interval firesTimer runningConsole logs 'tick'Timer runningNo re-renderNo DOM change
3User triggers unmountTimer runningCall cleanup: clearIntervalTimer stoppedNo re-renderTimer div removed
4After unmountTimer stoppedNo actionNo componentNo re-renderNo DOM element
💡 Component unmounted, cleanup done, no more timer or DOM element
Variable Tracker
VariableStartAfter 1After 2After 3Final
id (timer ID)undefinedsetInterval IDsetInterval IDclearedcleared
Component mountedfalsetruetruefalsefalse
Key Moments - 2 Insights
Why do we return a function inside useEffect?
The returned function is React's way to run cleanup before unmounting, as shown in step 3 of the execution_table where clearInterval is called.
Does the component re-render when it unmounts?
No, unmounting removes the component from the DOM without re-rendering, as seen in step 3 and 4 where no re-render happens.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 3?
AThe interval timer is set
BThe component re-renders
CThe cleanup function clears the interval and component unmounts
DNothing happens
💡 Hint
Check the 'Action' and 'DOM Change' columns at step 3 in execution_table
According to variable_tracker, what is the state of 'id' after step 3?
Acleared (timer stopped)
BsetInterval ID active
Cundefined
Dnull
💡 Hint
Look at the 'id (timer ID)' row after 'After 3' column in variable_tracker
If the cleanup function was missing, what would happen when the component unmounts?
AReact would automatically clear the timer
BThe timer would keep running causing potential bugs
CThe component would not unmount
DNothing changes
💡 Hint
Think about the purpose of the cleanup function shown in step 3 of execution_table
Concept Snapshot
Unmounting phase in React:
- Happens when component is removed from UI
- useEffect cleanup function runs here
- Cleanup stops timers, subscriptions, etc.
- No re-render during unmount
- Prevents memory leaks and bugs
Full Transcript
In React, the unmounting phase occurs when a component is removed from the screen. React first runs any cleanup functions returned by useEffect hooks. For example, if a timer was set, the cleanup function clears it. Then React removes the component's DOM elements. This prevents leftover processes and memory leaks. The component does not re-render during unmounting. This flow ensures clean removal of components and their side effects.

Practice

(1/5)
1. What is the main purpose of the unmounting phase in React components?
easy
A. To initialize state when the component first appears
B. To update the component when props change
C. To render the component's UI on the screen
D. To clean up resources like timers or event listeners before the component is removed

Solution

  1. Step 1: Understand the unmounting phase

    The unmounting phase happens when a component is about to be removed from the screen.
  2. 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.
  3. Final Answer:

    To clean up resources like timers or event listeners before the component is removed -> Option D
  4. Quick Check:

    Unmounting phase = cleanup before removal [OK]
Hint: Unmounting phase means cleaning up before component disappears [OK]
Common Mistakes:
  • Confusing unmounting with mounting or updating phases
  • Thinking unmounting initializes state
  • Believing unmounting is for rendering UI
2. Which of the following is the correct way to add a cleanup function inside a React useEffect hook?
easy
A. useEffect(() => { return () => { clearTimeout(timer); }; }, []);
B. useEffect(() => { clearTimeout(timer); }, []);
C. useEffect(() => { () => clearTimeout(timer); }, []);
D. useEffect(() => { return clearTimeout(timer); }, []);

Solution

  1. Step 1: Recall useEffect cleanup syntax

    The cleanup function must be returned from the function passed to useEffect.
  2. 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.
  3. Final Answer:

    useEffect(() => { return () => { clearTimeout(timer); }; }, []); -> Option A
  4. Quick Check:

    Cleanup function is returned inside useEffect [OK]
Hint: Cleanup must be a returned function inside useEffect [OK]
Common Mistakes:
  • Calling cleanup directly instead of returning a function
  • Not returning anything from useEffect
  • Returning the cleanup call instead of a function
3. What will be logged to the console when the following component unmounts?
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>;
}
medium
A. Nothing is logged on unmount
B. 'Tick' then 'Cleanup' immediately on unmount
C. 'Cleanup' logged once on unmount
D. Multiple "Tick" logs after unmount

Solution

  1. 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'.
  2. 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.
  3. Final Answer:

    'Cleanup' logged once on unmount -> Option C
  4. Quick Check:

    Cleanup logs once on unmount [OK]
Hint: Cleanup runs once on unmount, stopping intervals [OK]
Common Mistakes:
  • Thinking 'Tick' logs after unmount
  • Expecting no logs on unmount
  • Confusing cleanup timing with effect start
4. Identify the error in this React component related to unmounting:
import React, { useEffect } from 'react';

function Listener() {
  useEffect(() => {
    window.addEventListener('resize', () => console.log('Resized'));
  }, []);
  return <div>Listening</div>;
}
medium
A. The event listener callback should be named function, not arrow function
B. Missing cleanup function to remove the event listener on unmount
C. useEffect should not have an empty dependency array
D. Event listener should be added inside the return statement

Solution

  1. Step 1: Check event listener setup

    The component adds a resize event listener on mount but does not remove it on unmount.
  2. Step 2: Identify missing cleanup

    Without cleanup, the listener stays active after unmount, causing memory leaks or bugs.
  3. Final Answer:

    Missing cleanup function to remove the event listener on unmount -> Option B
  4. Quick Check:

    Always remove listeners in cleanup [OK]
Hint: Always remove event listeners in cleanup function [OK]
Common Mistakes:
  • Forgetting to remove event listeners on unmount
  • Thinking arrow functions can't be event callbacks
  • Misusing dependency arrays in useEffect
5. You have a React component that sets up a WebSocket connection in 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?
}, []);
hard
A. Return a cleanup function that calls socket.close() to close the connection
B. Call socket.close() immediately after setting onmessage
C. Do nothing; WebSocket closes automatically on unmount
D. Set socket = null in the cleanup function

Solution

  1. Step 1: Understand WebSocket lifecycle in React

    WebSocket connections stay open until explicitly closed. They do not close automatically on component unmount.
  2. Step 2: Implement cleanup to close connection

    Returning a cleanup function that calls socket.close() ensures the connection closes when the component unmounts, preventing resource leaks.
  3. Final Answer:

    Return a cleanup function that calls socket.close() to close the connection -> Option A
  4. Quick Check:

    Close WebSocket in cleanup function [OK]
Hint: Close WebSocket inside cleanup function returned by useEffect [OK]
Common Mistakes:
  • Closing WebSocket immediately instead of on unmount
  • Assuming WebSocket closes automatically
  • Setting socket to null without closing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard