Section650

Writing

TopicWeb development
Reading6 min

React Component Lifecycle: Mounting, Unmounting and Hooks

How a React component mounts and unmounts, from constructor and componentDidMount to useEffect setup and cleanup. Includes a corrected class example, its hooks equivalent, and how to fetch data today.

By Ka Lun Chan · Web development

What happens when a React component mounts and unmounts?

On mount, React creates the component, renders it, commits the result to the DOM and then runs your setup code: componentDidMount in a class, or useEffect in a function component. On unmount it runs your cleanup code, componentWillUnmount or the function your effect returns. Setup and cleanup should mirror each other.

I first wrote this on my old blog, when class components were how most of us wrote React. This version keeps that walkthrough, fixes a bug in my original cleanup example, and adds how the same ideas look with hooks, which React now recommends for new code.

React’s reference still documents class components and still supports them, so the class lifecycle matters whenever you maintain older code. The mapping to hooks is close enough that understanding one makes the other easier.

Fig. 639-1 Class lifecycle methods and their hook equivalents
Class methodHook equivalentNote
constructoruseState(initialValue)Initial state. A lazy initializer handles expensive setup.
UNSAFE_componentWillMountNoneLegacy. Put state in the constructor or useState, side effects in an Effect.
renderThe function bodyMust stay pure. Strict Mode calls it twice in development.
componentDidMountuseEffect(setup, [])Runs after the first commit. Subscribe, start timers, connect.
componentDidUpdateuseEffect(setup, [deps])Re-runs when a dependency changes, after cleaning up the old run.
componentWillUnmountThe cleanup function returned by setupUndo whatever setup did: clear timers, abort requests, remove listeners.
componentDidCatchNone yetError boundaries still need a class, or a small library that wraps one.

Which lifecycle methods run when a class component mounts?

In order: constructor, then render, then componentDidMount. The old componentWillMount sat between the constructor and render, but it’s deprecated and you shouldn’t use it in new code.

The constructor is where you set initial state by assigning this.state. A subclass can’t use this until it calls super, and you call super(props) if you want this.props inside the constructor. A class field (state = { movies: [] }) does the same job with less ceremony.

In my original post I called componentWillMount probably the least useful lifecycle method, and quoted React’s own advice to use the constructor instead. That held up. React renamed it UNSAFE_componentWillMount, and the current reference says it exists only for historical reasons. The React team’s explanation was practical: fetching there never avoided the empty first render, it ran during server rendering where the data was thrown away, and subscriptions added there could leak because componentWillUnmount is only guaranteed after componentDidMount.

render runs on mount and on every update. It should be pure: return JSX from props and state, and leave side effects to the lifecycle methods.

componentDidMount runs after React has put the component in the DOM. It’s still the right place in a class to fetch data, start a timer, add a listener or initialise a library that needs a real DOM node.

What belongs in componentWillUnmount?

Everything that undoes componentDidMount: clear intervals and timeouts, cancel network requests, remove event listeners, unsubscribe and tear down any library you initialised. It runs just before React removes the component.

My original example got this wrong. I wrote “time to clean up” and then put clearInterval(this.interval) inside componentWillMount, which runs before the component is even rendered, so the interval it was meant to stop didn’t exist yet. The cleanup belongs in componentWillUnmount. I also listed componentWillUnmount as part of mounting. It’s the only method in the unmounting phase.

Here is the same Movies component, corrected for current React. It fetches with fetch and an AbortController rather than axios (axios accepts the same signal option), refreshes every minute, and cleans up both the timer and the request:

Class component: setup in componentDidMount, cleanup in componentWillUnmount
import { Component } from 'react';

class Movies extends Component {
  constructor(props) {
    super(props);
    this.state = { movies: [], error: null };
  }

  componentDidMount() {
    this.controller = new AbortController();
    this.loadMovies();
    this.interval = setInterval(() => this.loadMovies(), 60000);
  }

  componentWillUnmount() {
    // The cleanup the original put in componentWillMount by mistake
    clearInterval(this.interval);
    this.controller.abort();
  }

  async loadMovies() {
    try {
      const response = await fetch(apiConfig.url, { signal: this.controller.signal });
      if (!response.ok) throw new Error('HTTP ' + response.status);
      const data = await response.json();
      this.setState({ movies: data.results });
    } catch (error) {
      if (error.name !== 'AbortError') this.setState({ error });
    }
  }

  render() {
    if (this.state.error) return <div role="alert">Could not load movies.</div>;
    return (
      <ul>
        {this.state.movies.map((movie) => <li key={movie.id}>{movie.title}</li>)}
      </ul>
    );
  }
}

Read the two methods side by side. Each line in componentWillUnmount reverses one in componentDidMount. When they don’t match, you get timers firing after the user has left the page and state updates on components that no longer exist.

How do you write the same component with hooks?

Use useState for the state and one useEffect for the timer and the request. The effect’s body is the setup, the function it returns is the cleanup, and the dependency array decides when it runs again.

Function component: useEffect with cleanup and AbortController
import { useEffect, useState } from 'react';

function Movies() {
  const [movies, setMovies] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    async function loadMovies() {
      try {
        const response = await fetch(apiConfig.url, { signal: controller.signal });
        if (!response.ok) throw new Error('HTTP ' + response.status);
        const data = await response.json();
        setMovies(data.results);
      } catch (err) {
        if (err.name !== 'AbortError') setError(err);
      }
    }

    loadMovies();
    const interval = setInterval(loadMovies, 60000);

    // Cleanup: runs on unmount, and before the effect re-runs
    return () => {
      clearInterval(interval);
      controller.abort();
    };
  }, []);

  if (error) return <div role="alert">Could not load movies.</div>;
  return (
    <ul>
      {movies.map((movie) => <li key={movie.id}>{movie.title}</li>)}
    </ul>
  );
}

The dependency array replaces the split between componentDidMount and componentDidUpdate. With no array, the effect runs after every commit. An empty array means once after the first commit. With values in the array, React re-runs it when one of them changes, and it runs the previous cleanup first. If Movies took a genre prop, adding genre to the array would abort the old request and start a new one, which a class needed both methods to handle.

The bigger change is that setup and cleanup sit together. In a class, related logic is split across methods by timing. In a function component it’s grouped by what it does, and unrelated jobs get separate effects. For how props and state feed into all this, see React components, state and props.

Why does my effect run twice in development?

Because StrictMode runs one extra setup and cleanup cycle for every effect in development, before the real setup. It does the same for classes, calling componentDidMount, componentWillUnmount, then componentDidMount again. Production runs setup once.

This is a test of the mirror rule above. If your cleanup really undoes your setup, the user can’t tell the difference. If it doesn’t, you see two intervals, two subscriptions or a doubled request, and you’ve found a bug before your users did. In the examples above, the first request is aborted and the first interval cleared, so nothing leaks.

The fix is a correct cleanup function. Removing StrictMode or adding a “has this run” ref only hides the problem.

Should you still fetch data in componentDidMount or useEffect?

It works, and the examples above are correct, but React’s docs now recommend something else for most apps: use your framework’s data loading if you have one, or a client-side cache such as TanStack Query if you don’t. Raw effects make caching, deduplication and server rendering hard to add later.

When I wrote the original, componentDidMount was the standard answer. Today the React team treats effects as an escape hatch for synchronising with systems outside React, and its guide You Might Not Need an Effect is worth reading in full. Derived values should be calculated during render, and logic that responds to a click belongs in the event handler. Fetching is a legitimate effect, but every component that does it by hand re-solves loading states, errors, races and caching.

A data library takes that off your hands. TanStack Query passes an abort signal to your query function, caches by key, shares one request between components and refetches on an interval:

The same Movies list with TanStack Query
import { useQuery } from '@tanstack/react-query';

function Movies() {
  const { data, error, isPending } = useQuery({
    queryKey: ['movies'],
    queryFn: async ({ signal }) => {
      const response = await fetch(apiConfig.url, { signal });
      if (!response.ok) throw new Error('HTTP ' + response.status);
      return (await response.json()).results;
    },
    refetchInterval: 60000,
  });

  if (isPending) return <div>Loading…</div>;
  if (error) return <div role="alert">Could not load movies.</div>;
  return (
    <ul>
      {data.map((movie) => <li key={movie.id}>{movie.title}</li>)}
    </ul>
  );
}

In a framework such as Next.js or React Router, data usually loads in a route loader or a Server Component before the component renders. That’s also where React’s use API fits: the loader or Server Component creates a promise, passes it down, and the component reads it with use(promise) inside a Suspense boundary. The promise has to be created outside render or cached, because a new promise on every render keeps the component suspended. I cover the server side in server-side rendering React with Next.js, and the Rails version in React with a Rails backend.

The lifecycle hasn’t gone away underneath any of this. Libraries still subscribe on mount and clean up on unmount. Knowing what they do for you is what lets you debug them when a request fires twice or a timer outlives its page.

Sources

Checked in November against react.dev’s Component, useEffect, StrictMode and use references, its You Might Not Need an Effect guide, the React team’s post on async rendering and the TanStack Query docs. The table and the Movies examples are mine.

Short answers

What is the useEffect equivalent of componentDidMount and componentWillUnmount?

An effect with an empty dependency array runs once after the first commit, like componentDidMount. The function it returns is the cleanup, which runs on unmount like componentWillUnmount. Add values to the array and the effect also covers componentDidUpdate, cleaning up before each re-run.

Should I still use componentWillMount?

No. It was renamed UNSAFE_componentWillMount and React says it exists only for historical reasons. Set initial state in the constructor or with useState, and move side effects such as fetching or subscriptions to componentDidMount or an effect.

Why does useEffect run twice in development?

StrictMode runs one extra setup and cleanup cycle for every effect in development to check that your cleanup undoes your setup. Production runs it once. If you see duplicated timers or requests, fix the cleanup rather than removing StrictMode.

Is useEffect the right place to fetch data?

It works with a proper cleanup, but React recommends your framework’s data loading if you use one, or a client-side cache such as TanStack Query otherwise. Those handle caching, deduplication, cancellation and race conditions that hand-written effects have to solve each time.

Check your cleanups

Pick one component that fetches or subscribes, turn on StrictMode and watch the network tab. If anything happens twice that shouldn’t, its cleanup is the first thing to fix.

Tell me what you’re building