Tutorials React JS Component Lifecycle
Ch 11 / 47
Chapter 11 Intermediate 13 min read React JS

Component Lifecycle

Every React component is born, lives, and dies. This journey through mounting, updating, and unmounting is called the component lifecycle. Understanding it is what separates developers who guess at timing bugs from those who know exactly when code runs. In this chapter you'll master every lifecycle phase, every method, their modern useEffect hook equivalents, and see real-world patterns — API fetching, subscriptions, cleanup, and error boundaries — all with clear diagrams and code.

Advertisement
What you'll learn
The 3 lifecycle phases — mounting, updating, unmounting
Mounting methods — constructor, render, componentDidMount
Updating methods — shouldComponentUpdate, componentDidUpdate
Unmounting method — componentWillUnmount and cleanup
Error boundary methods — getDerivedStateFromError, componentDidCatch
useEffect equivalents — every lifecycle method mapped to hooks
Real-world patterns — API calls, subscriptions, timers, cleanup
Common lifecycle pitfalls — infinite loops, memory leaks, stale closures

1. What is the Component Lifecycle?

Every React component goes through a predictable sequence of events from the moment it first appears on screen to when it's removed. This sequence is called the component lifecycle.

React divides the lifecycle into three phases. In each phase, React calls specific methods on your component so you can run your own code at exactly the right moment:

Mounting
The component is created and inserted into the DOM for the first time. This is where you initialise state, fetch initial data, and set up subscriptions.
Born — appears on screen
Updating
The component re-renders because state or props changed. This is where you react to changes — sync data, update external systems, optimise performance.
Lives — updates over time
Unmounting
The component is removed from the DOM. This is where you clean up — cancel timers, remove event listeners, close WebSocket connections to prevent memory leaks.
Dies — removed from screen
Why lifecycle matters Without lifecycle awareness you end up with memory leaks (forgetting to cancel subscriptions), infinite render loops (calling setState in the wrong place), and stale data (not re-fetching when props change). The lifecycle is the foundation for writing correct, professional React code.

2. Full Lifecycle Diagram

Here is the complete sequence of methods React calls in each phase. Methods in purple run in every phase; green = mount only; blue = update only; red = unmount only; orange = error only.

React Component Lifecycle — All Methods
Mounting
constructor()
Init state & bind
optional
↓
render()
Returns JSX
required
↓
componentDidMount()
DOM ready — fetch data
optional
Updating
getDerivedStateFromProps()
Sync state from props
rare
↓
shouldComponentUpdate()
Skip re-render?
perf
↓
render()
New JSX snapshot
required
↓
getSnapshotBeforeUpdate()
Capture DOM before paint
rare
↓
componentDidUpdate()
React to changes
optional
Unmounting
componentWillUnmount()
Cleanup before removal
cleanup!
Error
getDerivedStateFromError()
Show fallback UI
boundary
↓
componentDidCatch()
Log the error
boundary

3. Mounting Phase — Component Born

Mounting is the first time a component appears in the DOM. React runs these methods in this exact order, once only:

constructor(props)
Runs before the component mounts. Use it to initialise state and bind event handlers. Must call super(props) first. Do not call setState here — just assign this.state directly.
optional — only needed if you have state or bindings
Hook equivalent: useState() initialiser
render()
Required. Returns the JSX that describes what the component should look like. Must be pure — same state+props always produces same JSX. Never call setState, never perform side effects, never access the DOM here.
required — must return JSX or null
Hook equivalent: the function body itself
componentDidMount()
Runs after the component's output has been inserted into the DOM. This is the place to: fetch initial data from an API, set up subscriptions, add event listeners, start timers, or measure DOM elements. Calling setState here triggers a second render — React batches it before the browser paints.
optional — most-used lifecycle method
Hook equivalent: useEffect(() => {'{...}'}, [])
jsx — UserProfile.jsx — mounting phase in action
class UserProfile extends Component {

  // 1. constructor — initialise state before render
  constructor(props) {
    super(props);
    this.state = {
      user:    null,
      loading: true,
      error:   null,
    };
  }

  // 3. componentDidMount — DOM is ready, fetch data
  componentDidMount() {
    fetch(`/api/users/${this.props.userId}`)
      .then(r  => r.json())
      .then(user => this.setState({ user, loading: false }))
      .catch(err => this.setState({ error: err.message, loading: false }));
  }

  // 2. render — pure snapshot of state → JSX
  render() {
    const { user, loading, error } = this.state;
    if (loading) return <p>Loading…</p>;
    if (error)   return <p>Error: {error}</p>;
    return (
      <div>
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    );
  }
}

4. Updating Phase — Component Changes

An update is triggered when state changes (setState), props change (parent re-renders), or forceUpdate() is called. React calls these methods in order:

static getDerivedStateFromProps(props, state)
Called on every render (mount and update). Returns an object to merge into state, or null to change nothing. Use only when state must be computed directly from props. It's a static method — no access to this. Rarely needed in practice; derived state often causes bugs.
rare — use with caution
shouldComponentUpdate(nextProps, nextState)
Return true to allow the re-render, false to skip it. React calls render only if this returns true (default). Used for manual performance optimisation in expensive components. React.PureComponent does a shallow comparison automatically.
optional — performance optimisation
Hook equivalent: React.memo()
render()
Same method as mount — called again to produce updated JSX. React diffs the new output against the previous one (reconciliation) and updates only what changed in the real DOM.
required — runs on every update
getSnapshotBeforeUpdate(prevProps, prevState)
Called right before React applies changes to the DOM — after render but before commit. Return a value (the "snapshot") that is passed as the third argument to componentDidUpdate. Use case: capture scroll position before a list update, then restore it after.
rare — scroll preservation use case
componentDidUpdate(prevProps, prevState, snapshot)
Runs after every update. Perfect for reacting to prop or state changes — e.g. re-fetch data when a prop ID changes. Always compare previous and current values before calling setState to avoid infinite loops.
optional — most important update method
Hook equivalent: useEffect(() => {'{...}'}, [dep])
jsx — componentDidUpdate — safe pattern with comparison
componentDidUpdate(prevProps, prevState) {

  // ✅ ALWAYS compare — avoid calling setState unconditionally!
  if (this.props.userId !== prevProps.userId) {
    // userId prop changed — re-fetch
    this.setState({ loading: true });
    fetch(`/api/users/${this.props.userId}`)
      .then(r => r.json())
      .then(user => this.setState({ user, loading: false }));
  }

  // ❌ NEVER do this — setState without a guard = infinite loop!
  // this.setState({ count: this.state.count + 1 });
}
Advertisement

5. Unmounting Phase — Component Dies

When a component is removed from the DOM — because a parent stopped rendering it, a route changed, or a conditional switched to false — React calls one final method.

componentWillUnmount()
Called just before the component is destroyed. This is your one and only chance to clean up anything that would keep running after the component is gone. You cannot call setState here — the component is about to be removed; a new render would be wasted.
critical — prevents memory leaks
Hook equivalent: return () => {'{ cleanup }'} from useEffect
jsx — cleanup patterns in componentWillUnmount
class LiveFeed extends Component {
  componentDidMount() {
    // Set up things that need cleanup
    this.timer = setInterval(() => this.fetchLatest(), 5000);
    this.ws    = new WebSocket('wss://api.example.com/feed');
    window.addEventListener('resize', this.handleResize);
    document.addEventListener('keydown', this.handleKey);
  }

  componentWillUnmount() {
    // ✅ Cancel / remove everything set up in componentDidMount
    clearInterval(this.timer);            // stop the timer
    this.ws.close();                      // close WebSocket
    window.removeEventListener('resize', this.handleResize);
    document.removeEventListener('keydown', this.handleKey);
    // Abort any in-flight fetch if using AbortController
    this.abortCtrl?.abort();
  }

  render() { return <div>Live Feed</div>; }
}
The golden rule of cleanup For every setup in componentDidMount, there must be a corresponding teardown in componentWillUnmount. If you open a WebSocket, close it. If you start a timer, clear it. If you add an event listener, remove it. Forgetting this causes memory leaks — the component is gone but its callbacks keep running and accumulating.

6. Error Boundaries — Catching Render Errors

If a component throws an error during rendering, React normally unmounts the entire tree — the whole app goes blank. Error Boundaries catch render errors in their subtree and show a fallback UI instead. They are the only place where you must use class components in modern React.

static getDerivedStateFromError(error)
Called during the render phase when a child throws. Return an object to update state so the next render shows the fallback UI. No side effects here — it runs during rendering.
show fallback UI
componentDidCatch(error, info)
Called after an error has been thrown by a child component. Receives the error and an info object with componentStack. Good for logging — send to Sentry, LogRocket, etc.
log error to monitoring service
jsx — ErrorBoundary.jsx — production-ready error boundary
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, message: '' };
  }

  // 1. Called during render — update state to show fallback
  static getDerivedStateFromError(error) {
    return { hasError: true, message: error.message };
  }

  // 2. Called after render — log to monitoring
  componentDidCatch(error, info) {
    console.error('Error caught:', error);
    console.error('Component stack:', info.componentStack);
    // sendToSentry(error, info);  ← log to error monitoring
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong 😔</h2>
          <p>{this.state.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage — wrap any subtree you want to protect
<ErrorBoundary>
  <UserDashboard />
</ErrorBoundary>
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
Lifecycle, Hooks, State, Context, Router, Redux, REST APIs & 6 real-world projects — guided by experts with 100% placement support in Vadodara.
Lifecycle & Hooks State Management React Router Redux Toolkit REST APIs 6 Projects Certificate
2,500+Students
6+Projects
3–6Months
100%Placement

7. Lifecycle → useEffect Equivalents

In functional components, the useEffect hook replaces all three lifecycle phases in one consistent API. The key is the dependency array:

Class Lifecycle Method useEffect Equivalent When it runs
componentDidMount() useEffect(() => {'{ }'}, []) Once, after first render
componentDidUpdate(prev, state) useEffect(() => {'{ }'}, [dep]) After render when dep changes
componentDidUpdate() (any) useEffect(() => {'{ }'}) After every render
componentWillUnmount() useEffect(() => {'{ return () => cleanup }'}, []) Cleanup function on unmount
didMount + willUnmount useEffect(() => {'{ setup; return cleanup }'}, []) Setup on mount, cleanup on unmount
jsx — same UserProfile using useEffect hooks
import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user,    setUser]    = useState(null);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState(null);

  // ✅ componentDidMount + componentDidUpdate(prevProps.userId ≠ userId)
  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then(r => r.json())
      .then(d => { setUser(d); setLoading(false); })
      .catch(e => {
        if (e.name !== 'AbortError') { setError(e.message); setLoading(false); }
      });

    // ✅ componentWillUnmount — cancel in-flight request
    return () => controller.abort();
  }, [userId]); // re-runs when userId changes

  if (loading) return <p>Loading…</p>;
  if (error)   return <p>Error: {error}</p>;
  return <div><h2>{user?.name}</h2></div>;
}
useEffect is composable Unlike class lifecycle methods, you can have multiple useEffect calls in one component — each handling a separate concern. This is much cleaner than putting unrelated logic in the same componentDidMount. Put each concern in its own effect with its own dependencies.

8. Common Lifecycle Pitfalls

Most lifecycle bugs come from the same few mistakes. Here are the ones every React developer hits:

Infinite Loop in componentDidUpdate
Calling setState inside componentDidUpdate without a condition triggers another update, which calls componentDidUpdate again — forever. Always compare prevProps/prevState first.
Most common bug
Memory Leak — setState After Unmount
A fetch started in componentDidMount may resolve after the component unmounts. Calling setState on an unmounted component causes a warning. Use an AbortController or an isMounted flag to cancel.
Memory leak
Missing Dependency in useEffect
If you read a prop or state inside useEffect but don't list it in the dependency array, the effect captures a stale value from the first render. Always include every value read inside the effect in its deps.
Stale closure
Side Effects in render()
Calling fetch(), localStorage.setItem(), or modifying the DOM directly inside render() is wrong. The render must be pure — side effects belong in componentDidMount or useEffect.
Impure render
Forgetting Cleanup
Adding an event listener or starting a setInterval in componentDidMount without a matching removal in componentWillUnmount accumulates handlers and causes bugs when the component mounts/unmounts repeatedly.
Memory leak
Calling setState in constructor
The constructor runs before the component mounts — calling setState here causes a warning. In the constructor, assign this.state = {'{...}'} directly; call setState only after mounting.
Beginner mistake
Advertisement
Knowledge Check — Component Lifecycle
Q1. In what order do React lifecycle methods run on first render?
On first mount, the order is:

1. constructor() — if defined, runs first. Initialises state and binds methods.
2. static getDerivedStateFromProps() — runs before render on mount and every update. Returns state update or null.
3. render() — returns JSX. Must be pure.
4. componentDidMount() — runs after the component is inserted into the DOM. Safe to fetch data and add subscriptions here.

Note: render() runs before the DOM is ready; componentDidMount() runs after the DOM is ready. This distinction matters for DOM measurements and API calls.
Q2. Why do you need to compare prevProps in componentDidUpdate?
componentDidUpdate runs after every update — every time any state or prop changes.

If you call setState() inside it without a guard, it triggers another update → which calls componentDidUpdate again → which calls setState again → infinite loop.

By comparing prevProps.userId !== this.props.userId, you ensure your code only runs when the specific thing you care about actually changed. The comparison is the guard that breaks the loop.
Q3. What is the functional component equivalent of componentWillUnmount?
The equivalent is the cleanup function returned from useEffect:

useEffect(() => {'{ setup(); return () => cleanup(); }'}, [])

React calls the returned cleanup function when the component unmounts (or before the effect re-runs if dependencies changed).

Rule: If your useEffect sets something up (event listener, timer, subscription, WebSocket), the return function should tear it down.
Q4. Why are Error Boundaries still class components in React 18?
Error Boundaries require componentDidCatch() and getDerivedStateFromError(). As of React 18, there is no Hook equivalent for these two methods.

The React team has acknowledged this gap. A use() API and improved error handling are being discussed for future versions, but for now Error Boundaries remain the one case where you must write a class component in new code.

In practice, most projects have just one or two Error Boundary class components wrapping major sections (like the whole app, or the main content area).
Multiple Choice
MCQ 1
Which lifecycle method is the correct place to make an initial API call?
MCQ 2
What does useEffect(() => {'{ }'}, []) map to in class components?
MCQ 3
You add a setInterval in componentDidMount. What must you do in componentWillUnmount?
MCQ 4
Which two methods make a class component an Error Boundary?
Chapter 11 Summary — Component Lifecycle
  • Every React component goes through 3 lifecycle phases: Mounting (born), Updating (lives), and Unmounting (dies).
  • Mounting order: constructor → getDerivedStateFromProps → render → componentDidMount. The DOM is only available after render completes.
  • componentDidMount() is the right place for API calls, subscriptions, timers, and DOM measurements.
  • componentDidUpdate(prevProps, prevState) reacts to changes. Always compare previous values before calling setState to avoid infinite loops.
  • componentWillUnmount() is cleanup time. Every setup in componentDidMount needs a corresponding teardown here — timers, listeners, WebSockets.
  • Error Boundaries use getDerivedStateFromError() to show fallback UI and componentDidCatch() to log errors. They must be class components.
  • useEffect with empty deps [] = componentDidMount. With deps = componentDidUpdate. Returned cleanup function = componentWillUnmount.
  • Common pitfalls: setState in componentDidUpdate without guard (infinite loop), no cleanup (memory leak), side effects in render (impure), missing useEffect deps (stale closure).
Practice — Build a Lifecycle Logger
Open the sandbox. Create a class component that logs each lifecycle phase to the console — constructor, render, componentDidMount, componentDidUpdate, componentWillUnmount. Add a toggle button to mount/unmount it and watch the lifecycle fire.
Open Vite + React Sandbox

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel