Skip to main content
React Introduction
CHAPTER 14 Beginner

React Component Lifecycle Basics

Updated: May 13, 2026
15 min read

# 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 useEffect hook 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 /dashboard page. 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 /dashboard page to the /about page. 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 array
12
### Simulating "Updating"
Run code when specific data changes.

jsx 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

12
### Simulating "Unmounting"
Run code right before the component is destroyed.

jsx id="ch14_ex3" useEffect(() => { return () => { console.log("Component Unmounted!"); // Good for: Clearing timers, closing websocket connections. }; }, []);

12345678910111213141516171819202122
## 5. Output Explanations
Understanding exactly *when* these functions fire is key to optimization. React guarantees that the cleanup function (Unmounting) will fire *before* the component is removed, allowing you to gracefully shut down background processes.

## 6. Real-World Examples
Imagine a `<VideoPlayer>` component.
- **Mount:** Establish a connection to the streaming server and start playing.
- **Update:** The user selects "1080p" instead of "720p". The `resolution` state changes, triggering an update to fetch higher-quality video chunks.
- **Unmount:** The user closes the tab. The cleanup function pauses the video and terminates the connection so it doesn't waste the user's bandwidth in the background.

## 7. Common Mistakes
- **Memory Leaks:** Forgetting to clear an interval timer on unmount. If the user navigates between pages 10 times, you will have 10 timers running in the background, slowing down the browser!
- **Over-rendering:** Putting complex logic directly inside the component body instead of an effect. The component body runs on *every* update phase.

## 8. Best Practices
- Conceptualize your logic based on data flow, not lifecycles. Instead of asking "What happens on mount?", ask "When my state changes, what needs to sync with it?"

## 9. Exercises
1. Write a `useEffect` that logs "Hello" on mount, and logs "Goodbye" on unmount. 

## 10. Mini Project: Timer Component
Let's build a StopWatch component that strictly relies on Mounting and Unmounting lifecycles to start and clear a timer.

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.

16. Next Chapter Recommendation

We've covered logic, state, and lifecycles. Now it's time to make things look beautiful. In Chapter 15: React Styling Techniques, we will explore the different ways to apply CSS to React applications, from inline styles to external stylesheets.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·