React Component Lifecycle Basics
# React Component Lifecycle Basics
1. Introduction
Every living thing has a lifecycle: it is born, it grows and changes, and eventually, it dies. React components are no different! They have a specific lifecycle: they are put onto the screen (Mounting), they change based on state/props (Updating), and they are removed from the screen (Unmounting). While modern React uses Hooks (useEffect) to handle these phases, understanding the underlying lifecycle concept is crucial for debugging and interviews.
2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the three main phases of a React component's lifecycle.
-
Map the
useEffecthook to these lifecycle phases.
- Understand when and why a component re-renders.
3. Beginner-Friendly Explanations
Phase 1: Mounting (Birth)
Mounting is when React creates the component and inserts its HTML into the real DOM for the very first time.-
Example: A user navigates to the
/dashboardpage. The<Dashboard>component is mounted.
Phase 2: Updating (Growth)
A component updates whenever its State or Props change. React re-runs the component function, generates new JSX, compares it to the old JSX, and updates the screen.-
Example: A user clicks a "Like" button. The state increments, and the
<LikeCount>component updates.
Phase 3: Unmounting (Death)
Unmounting is when a component is completely removed from the DOM.-
Example: The user navigates away from the
/dashboardpage to the/aboutpage. The<Dashboard>component is unmounted and destroyed to free up memory.
4. Mapping Lifecycle to useEffect
In the old days of React (Class Components), developers used methods named componentDidMount, componentDidUpdate, and componentWillUnmount. Today, we do all three using a single hook: useEffect.
Simulating "Mounting"
Run code only once when the component appears. ```jsx id="ch14_ex1" useEffect(() => { console.log("Component Mounted!"); // Good for: Initial API fetches. }, []); // Empty dependency arrayjsx id="ch14_ex2" useEffect(() => { console.log("User ID changed, fetching new user profile!"); // Good for: Reacting to prop/state changes. }, [userId]); // Runs when 'userId' updates
jsx id="ch14_ex3" useEffect(() => { return () => { console.log("Component Unmounted!"); // Good for: Clearing timers, closing websocket connections. }; }, []);
jsx id="ch14_proj1" // Example React component import React, { useState, useEffect } from 'react';
// The Child Component with lifecycles const Stopwatch = () => { const [seconds, setSeconds] = useState(0);
useEffect(() => { // 1. MOUNTING phase console.log("Stopwatch Mounted! Starting timer..."); const intervalId = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000);
// 2. UNMOUNTING phase return () => { console.log("Stopwatch Unmounted! Clearing timer..."); clearInterval(intervalId); // CRITICAL: Prevents memory leak }; }, []);
return ( <div className="text-4xl font-mono font-black text-blue-600 my-4"> {seconds}s </div> ); };
// The Parent Component export default function TimerDashboard() { const [showTimer, setShowTimer] = useState(true);
return ( <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4"> <div className="bg-white p-8 rounded-xl shadow border text-center max-w-sm w-full"> <h2 className="text-xl font-bold text-gray-800">React Lifecycle Demo</h2> {/* Conditional Rendering mounts/unmounts the component */} {showTimer && <Stopwatch />}
<button
onClick={() => setShowTimer(!showTimer)}
className={mt-4 w-full py-2 rounded font-bold transition ${
showTimer ? 'bg-red-500 hover:bg-red-600 text-white' : 'bg-green-500 hover:bg-green-600 text-white'
}}
>
{showTimer ? 'Destroy Timer (Unmount)' : 'Create Timer (Mount)'}
</button>
</div>
</div>
);
}
``
11. Coding Challenges
Challenge 1: Modify the Timer component to log "Timer Updated to X" on the Updating phase (every time the seconds state changes).12. MCQs with Answers
Q1: When a component is removed from the DOM, which lifecycle phase is it in? A) Mounting B) Updating C) Unmounting D) Rendering *Answer: C*Q2: How do you access the "Unmount" phase in modern React?
A) By calling the useUnmount hook.
B) By writing a componentWillUnmount function.
C) By returning a cleanup function from inside useEffect.
*Answer: C*
13. Interview Questions
- Q: What are the three phases of a React component's lifecycle?
- Q: How did the introduction of Hooks change how we handle component lifecycles?
14. FAQs
Do functional components have lifecycle methods? Technically, no. Class components have *methods* (like componentDidMount). Functional components rely on React Hooks to hook into the lifecycle events under the hood.
15. Summary
Understanding Mounting (birth), Updating (growth), and Unmounting (death) gives you a deeper mental model of how React operates. By using useEffect` with dependency arrays and cleanup functions, you have total control over a component from the moment it is created until it is destroyed.