-- online Search!

The Component Lifecycle

by kirupa   |   filed under Learning React

Every component you create has a life. It shows up on the screen, it changes as props and state change, and eventually it goes away when it is no longer needed. React keeps track of all of these moments, and we get a chance to run our own code at each one of them. If you've been following along, you have already done some of this without calling it out. When we set up a timer in our lightning counter, we were taking advantage of the component's life.

In this tutorial, we are going to look at the three main moments in a component's life, see how hooks let us react to each one, and also connect all of this to the lifecycle methods that you'll see in older React code and tutorials. Class components used to have a whole set of methods with names like componentDidMount. Even though we don't write those anymore, they are a useful way to think about what is going on, so we'll see where each one went.

Onwards!

Learning React by Kirupa Chinnathambi

OMG! A React Book Written by Kirupa?!!

To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.

BUY ON AMAZON

Mounting, Updating, and Unmounting

A component goes through three phases:

  • Mounting: The component is created and added to the screen for the very first time. React calls your function, takes the JSX it returns, and puts the result into the DOM.
  • Updating: The component is already on the screen, but something changed. It could be new props from a parent or new state (from a setState call). React calls your function again, compares the new JSX to the old, and updates only what is different. A component can update many times (or never).
  • Unmounting: The component is removed from the screen. This happens when a parent stops rendering it, which is what the {show && <Counter />} pattern from our earlier tutorials does when show turns false.

The cool thing is that in a function component, one hook takes care of all of these. We've met it already: useEffect. The following diagram shows where its different forms live in a component's life:

Three boxes labeled Mount, Update, and Unmount joined by arrows. Mount maps to useEffect with an empty array, which runs once. Update maps to useEffect with count in the array, which runs when count changes. Unmount maps to the cleanup function that an effect returns.

Let's turn this into something we can actually watch happen.

Watching a Component Live and Die

In a Vite project, replace the contents of your src/App.jsx file with the following. We have a SimpleCounter component that counts up once a second, and an App component with a button that adds or removes it:

import { useState, useEffect } from "react";

function SimpleCounter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Mounted: starting the timer");
    const id = setInterval(() => {
      setCount((c) => c + 1);
    }, 1000);

    return () => {
      console.log("Unmounting: stopping the timer");
      clearInterval(id);
    };
  }, []);

  useEffect(() => {
    console.log(`Updated: count is now ${count}`);
  }, [count]);

  return <p>Count: {count}</p>;
}

export default function App() {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow(!show)}>Toggle Counter</button>
      {show && <SimpleCounter />}
    </div>
  );
}

Run this, open your browser's console, wait a couple of seconds, and then click the Toggle Counter button. You should see something like the following:

Mounted: starting the timer
Updated: count is now 0
Unmounting: stopping the timer
Mounted: starting the timer
Updated: count is now 0
Updated: count is now 1
Updated: count is now 2
Unmounting: stopping the timer

Let's go through our code and then the output. Our component has two effects:

  • The first one has an empty dependency array, so it runs when the component mounts. It starts the timer. The function it returns is the clean-up, which runs when the component unmounts. It stops the timer. Notice how the code that starts the timer and the code that stops it sit right next to each other.
  • The second one depends on count, so it runs after the first render and then every time count changes. It just logs a message, but this is where you would put code that needs to react to an update.

Now the output. You may be wondering why we see Mounted, then Unmounting, and then Mounted again when we only showed the component once. (The Updated lines at the start are there because an effect with a dependency array also runs after the first render.) As we saw in the Effects with useEffect tutorial, this is Strict Mode at work. In development, React mounts a component, immediately unmounts it, and mounts it again to make sure our clean-up code is doing its job. In your production build, you would only see the second mount. After that, we see a message each time the count changes, and when we click the toggle button, the clean-up runs and the timer stops. If our clean-up were missing, the timer would carry on ticking for a component that no longer exists.

Note: Updates Don't Only Come from State

A component updates whenever its state changes, its props change, or a parent that renders it updates. When that happens, our component function runs again from the top. An effect is only called if one of the values in its dependency array is different from the last render, which is why the first effect above (with the empty array) stays quiet during updates.

 

What Happens During a Render

It helps to know a little about the order in which React does things. Each time something needs to change on the screen, React goes through three steps:

  1. Trigger: Something kicks things off. It is either the first time the component is shown, or a state update.
  2. Render: React calls your component functions to figure out what the screen should look like. At this point, nothing has been changed on the screen. This step should only calculate JSX, and it should not have side effects.
  3. Commit: React applies the differences to the DOM. After that, the browser paints the result, and your effects run.

All of the hooks we've seen fit into this flow. useState is read during the render step, and useEffect runs after the commit, which is why effects are the right place for the messy parts of our code.

From Lifecycle Methods to Hooks

If you read older React tutorials or work on an older app, you'll run into class components that use lifecycle methods. Here is how the common ones map to what we've been doing:

  • constructor: Setting up the starting state is done with useState(initialValue).
  • render: This is now the function component itself. Whatever you return is what gets rendered.
  • componentDidMount: useEffect(() => { ... }, []), an effect with an empty dependency array.
  • componentDidUpdate: useEffect(() => { ... }, [someValue]), an effect with the values you care about in the array.
  • componentWillUnmount: The function you return from an effect (the clean-up).
  • shouldComponentUpdate: memo, which skips rendering a component when its props haven't changed. We'll look at this in Avoiding Unnecessary Renders.
  • getDerivedStateFromProps: Usually just a value you calculate while rendering. You don't need any hook for it.
  • componentDidCatch and getDerivedStateFromError (error boundaries): These are the one area where classes are still needed, or you can use a small library like react-error-boundary. We'll go through this in Suspense and Error Boundaries.

Treat this list as a translation guide and not as a recipe. There's a subtle difference in how the two worlds think. With lifecycle methods, you asked, "What should happen when my component mounts? When it updates? When it unmounts?" and wrote code for each moment. With effects, you ask, "What outside thing does my component need to stay in sync with, and how do I start and stop that?" You write one effect that describes the setup and clean-up, and React figures out when to run it. That is why a single effect with the right dependency array can replace code that used to be spread across three different methods.

Conclusion

A component mounts, updates (possibly many times), and unmounts. With hooks, useState holds on to what the component remembers, and useEffect gives us a place to run code after each of those moments, with the clean-up function handling the unmount. The old lifecycle methods map neatly onto these, and now you can read class-based code without getting lost.

Before moving on, I should mention that the older lifecycle methods also include some rarely used ones that I didn't cover. If you ever need them, the React documentation for class components has you covered.

Up next, we'll look at a different kind of escape hatch: reaching into the DOM to grab an element directly.

Next tutorial: Accessing DOM Elements

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--