Bird
Raised Fist0
Reactframework~10 mins

Lifecycle mapping with hooks in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Lifecycle mapping with hooks
Component Mounts
↓
Initial Render Complete
↓
useEffect(() => { ... }, [
↓
State or Props Change
↓
Component Re-renders
↓
useEffect(() => { ... }, [deps
↓
Component Unmounts
↓
Cleanup Runs
This flow shows how React functional components use hooks to run code when mounting, updating, and unmounting.
Execution Sample
React
import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setCount(c => c + 1), 1000);
    return () => clearInterval(id);
  }, []);
  return <div>{count}</div>;
}
This Timer component increases count every second using useEffect to set up and clean up the interval.
Execution Table
StepTriggerState BeforeActionState AfterWhat Re-rendersDOM Change
1Component mountscount: undefinedInitialize count=0count: 0Timer componentRender <div>0</div>
2useEffect runs after mountcount: 0Set interval to increment count every 1scount: 0No immediate re-renderNo DOM change
31 second passescount: 0setCount increments count to 1count: 1Timer componentUpdate <div>1</div>
41 second passescount: 1setCount increments count to 2count: 2Timer componentUpdate <div>2</div>
5Component unmountscount: 2Cleanup: clearInterval calledcount: 2No re-renderInterval stops, DOM remains <div>2</div>
💡 Component unmounts, cleanup runs, interval stops, no further updates.
Variable Tracker
VariableStartAfter 1After 2After 3Final
countundefined0122
intervalIdundefinedid setid setid setcleared
Key Moments - 3 Insights
Why does useEffect run after the first render and not during it?
useEffect runs after the render to avoid blocking UI updates. See execution_table step 2 where effect sets interval only after initial render.
What happens if we forget to return a cleanup function in useEffect?
The interval would keep running even after unmount, causing memory leaks. Step 5 shows cleanup stopping the interval.
Why does the component re-render when count changes?
Calling setCount updates state, triggering React to re-render the component with new count. See steps 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of count at Step 3?
A1
B2
C0
Dundefined
💡 Hint
Check the 'State After' column at Step 3 in execution_table.
At which step does the cleanup function run?
AStep 3
BStep 5
CStep 2
DStep 1
💡 Hint
Look for 'Component unmounts' and 'Cleanup' in execution_table.
If we remove the empty dependency array in useEffect, what changes in the execution?
AEffect runs only once after mount
BCleanup never runs
CEffect runs after every render causing multiple intervals
DState never updates
💡 Hint
Dependency array controls when useEffect runs; see step 2 explanation.
Concept Snapshot
React functional components use useEffect hook to run code at key lifecycle points.
- useEffect with [] runs once after mount.
- Returning a function cleans up on unmount.
- State changes trigger re-renders.
- Effects run after render to keep UI responsive.
Full Transcript
This visual execution shows how React functional components use hooks to manage lifecycle events. When the component mounts, useState initializes state. Then useEffect runs after the first render to set up side effects like intervals. Each state update triggers a re-render, updating the DOM. When the component unmounts, the cleanup function runs to clear intervals and prevent leaks. This flow helps beginners see how hooks replace class lifecycle methods with simple, clear steps.

Practice

(1/5)
1. Which React hook is used to run code after a component renders, replacing lifecycle methods like componentDidMount and componentDidUpdate?
easy
A. useEffect
B. useState
C. useContext
D. useRef

Solution

  1. Step 1: Understand lifecycle replacement

    The useEffect hook runs code after rendering, replacing lifecycle methods like componentDidMount and componentDidUpdate.
  2. Step 2: Identify the correct hook

    useState manages state, useContext accesses context, and useRef stores mutable values. Only useEffect runs side effects after render.
  3. Final Answer:

    useEffect -> Option A
  4. Quick Check:

    Effect hook = useEffect [OK]
Hint: useEffect runs code after render like lifecycle methods [OK]
Common Mistakes:
  • Confusing useState with useEffect
  • Thinking useRef runs effects
  • Believing useContext triggers after render
2. Which of the following is the correct syntax to run an effect only once when a React component mounts using useEffect?
easy
A. useEffect(() => { /* code */ }, null);
B. useEffect(() => { /* code */ });
C. useEffect(() => { /* code */ }, true);
D. useEffect(() => { /* code */ }, []);

Solution

  1. Step 1: Understand dependency array usage

    Passing an empty array [] as the second argument to useEffect makes it run only once after the first render (component mount).
  2. Step 2: Analyze each option

    useEffect(() => { /* code */ }); runs after every render. useEffect(() => { /* code */ }, true); runs after every render since non-array dependencies are ignored. useEffect(() => { /* code */ }, null); with null also runs after every render as it's not an array.
  3. Final Answer:

    useEffect(() => { /* code */ }, []); -> Option D
  4. Quick Check:

    Empty array = run once [OK]
Hint: Empty dependency array runs effect once on mount [OK]
Common Mistakes:
  • Omitting dependency array causes effect every render
  • Using null instead of empty array
  • Passing non-array values like true or null as dependencies
3. What will be logged to the console when the following React component mounts and then the count state changes?
function Counter() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log('Count is', count);
  }, [count]);
  return  setCount(count + 1)}>Increment;
}
medium
A. Logs 'Count is 0' once on mount only
B. Logs 'Count is 0' repeatedly every second
C. Logs 'Count is 0' on mount and 'Count is 1' after first click
D. Logs nothing because useEffect has dependencies

Solution

  1. Step 1: Understand useEffect with dependency

    The effect runs after the component mounts and whenever count changes because count is in the dependency array.
  2. Step 2: Trace the console logs

    On mount, count is 0, so it logs 'Count is 0'. After clicking the button, count becomes 1, triggering the effect again and logging 'Count is 1'.
  3. Final Answer:

    Logs 'Count is 0' on mount and 'Count is 1' after first click -> Option C
  4. Quick Check:

    Effect runs on mount and dependency change [OK]
Hint: Effect runs on mount and when dependencies change [OK]
Common Mistakes:
  • Thinking effect runs only once without dependencies
  • Assuming no logs because dependencies exist
  • Confusing useEffect with setInterval
4. Identify the problem in this React component that uses useEffect and suggest the fix:
function Timer() {
  React.useEffect(() => {
    const id = setInterval(() => console.log('Tick'), 1000);
  }, []);
  return <div>Timer</div>;
}
medium
A. No problem; code works fine as is
B. Missing cleanup function to clear the interval on unmount
C. Dependency array should include 'id' to update interval
D. setInterval should be replaced with setTimeout

Solution

  1. Step 1: Analyze effect side effects

    The effect sets an interval but does not clear it, causing a memory leak when the component unmounts.
  2. Step 2: Suggest cleanup function

    Return a cleanup function from useEffect that calls clearInterval(id) to stop the interval on unmount.
  3. Final Answer:

    Missing cleanup function to clear the interval on unmount -> Option B
  4. Quick Check:

    Cleanup prevents memory leaks [OK]
Hint: Always clean intervals/timeouts in useEffect cleanup [OK]
Common Mistakes:
  • Forgetting to clear intervals causing leaks
  • Adding dependencies unnecessarily
  • Replacing setInterval with setTimeout incorrectly
5. You want to fetch user data only once when a component mounts and cancel the fetch if the component unmounts before it finishes. Which is the best way to implement this using useEffect?
hard
A.
useEffect(() => {
  const controller = new AbortController();
  fetch('/user', { signal: controller.signal })
    .then(res => res.json())
    .then(data => console.log(data));
  return () => controller.abort();
}, []);
B.
useEffect(() => {
  fetch('/user').then(res => res.json()).then(data => console.log(data));
}, []);
C.
useEffect(() => {
  fetch('/user').then(res => res.json()).then(data => console.log(data));
  return () => console.log('Cleanup');
}, []);
D.
useEffect(() => {
  fetch('/user').then(res => res.json()).then(data => console.log(data));
}, [fetch]);

Solution

  1. Step 1: Understand fetch cancellation

    To cancel a fetch request on unmount, use an AbortController and pass its signal to fetch.
  2. Step 2: Implement cleanup to abort fetch

    Return a cleanup function from useEffect that calls controller.abort() to cancel the fetch if unmount happens early.
  3. Final Answer:

    Use AbortController with cleanup to abort fetch -> Option A
  4. Quick Check:

    AbortController + cleanup = safe fetch [OK]
Hint: Use AbortController and cleanup to cancel fetch on unmount [OK]
Common Mistakes:
  • Not cancelling fetch causing memory leaks
  • Logging cleanup without aborting fetch
  • Adding fetch to dependencies unnecessarily
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