Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to React
React Component Lifecycle Explained

React Component Lifecycle Explained

ReactBy Muhammad Fareed
reactcomponentlifecycle

Short answer: every React component goes through three phases: mounting (added to the page), updating (re-rendered when props or state change) and unmounting (removed). In modern function components you hook into these phases with useEffect.

The three phases

PhaseWhenTypical work
MountingThe component first appearsFetch data, subscribe, start timers
UpdatingProps or state changeReact to a new value, re-fetch
UnmountingThe component is removedClean up listeners, timers, subscriptions

Lifecycle in function components

import { useEffect, useState } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  // Runs after mount, and again whenever userId changes
  useEffect(() => {
    const controller = new AbortController();

    fetch('/api/users/' + userId, { signal: controller.signal })
      .then((r) => r.json())
      .then(setUser)
      .catch(() => {});

    // Cleanup runs before the next effect and on unmount
    return () => controller.abort();
  }, [userId]);

  return <p>{user ? user.name : 'Loading...'}</p>;
}

How the dependency array controls timing

CodeRuns
useEffect(fn, [])Once after the first render (mount); cleanup on unmount
useEffect(fn, [a, b])After mount and whenever a or b changes
useEffect(fn)After every render

Learn both hooks in depth in useState and useEffect.

Class component lifecycle methods and their hook equivalents

Class methodPurposeHook version
constructorSet initial stateuseState(initial)
renderReturn the UIThe function body
componentDidMountRuns after the first renderuseEffect(fn, [])
componentDidUpdateRuns after updatesuseEffect(fn, [deps])
componentWillUnmountCleanupReturn a function from useEffect
shouldComponentUpdateSkip re-rendersReact.memo
class Clock extends React.Component {
  state = { time: new Date() };

  componentDidMount() {
    this.timer = setInterval(() => this.setState({ time: new Date() }), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  render() {
    return <p>{this.state.time.toLocaleTimeString()}</p>;
  }
}

Class components still work, but new code uses function components and hooks.

Render vs commit

  1. Render: React calls your component to work out what the UI should look like. This must be pure, with no side effects.
  2. Commit: React updates the DOM.
  3. Effects: useEffect runs after the browser paints.

Use useLayoutEffect only when you must measure or change the layout before paint.

Strict Mode in development

In development, React Strict Mode mounts, unmounts and mounts a component again to expose missing cleanup. If your effect breaks when it runs twice, add a proper cleanup function. This extra run does not happen in production.

Common mistakes

  • Forgetting cleanup for timers, event listeners and subscriptions, causing leaks.
  • Leaving out dependencies, which leads to stale values.
  • Updating state after unmount from an unfinished request; abort it as shown above.
  • Using effects to compute values that can be calculated during rendering.

Frequently asked questions

Why does my useEffect run twice in development?

In React Strict Mode, React deliberately mounts, unmounts and remounts components in development to help find missing cleanup. This does not happen in production builds.

What is the equivalent of componentWillUnmount in hooks?

Return a cleanup function from useEffect. React runs it when the component unmounts and also before the effect runs again.

Should I still learn class lifecycle methods?

Learn the idea, because you will meet class components in older code. For new code, function components with hooks are the standard approach.

Next steps

Read the hooks guide, speed things up with performance optimization, or start from what React is.