← Back to React, page 1

react-0004 · Medium mid

How do class lifecycle methods map to function components, and how does useEffect replace them?

A class component has mounting, updating and unmounting phases with methods such as componentDidMount, componentDidUpdate and componentWillUnmount. A function component expresses the same work with useEffect. The effect runs after render, its cleanup runs before the next run and on unmount, and the dependency array decides when it re-runs. Think "keep this in sync with these values", not "run on mount".

Full answer

A class component lives through three phases. It mounts (constructor, render, componentDidMount), it updates when props or state change (render, componentDidUpdate), and it unmounts (componentWillUnmount). Two more methods handle errors: getDerivedStateFromError and componentDidCatch.

A function component has no phases. It has renders, and each render can ask React to run an effect afterward. The rough map is:

  • componentDidMount: an effect with an empty dependency array.
  • componentDidUpdate: an effect whose dependency array lists the values that matter.
  • componentWillUnmount: the cleanup function returned from an effect.

The map is only rough, and the old mental model causes bugs. An effect is not "on mount" or "on update". It describes how to synchronise with something outside React for the current values of props and state. When those values change, React runs the previous cleanup and then the effect again with the new values.

Look at the chat room example in the code. A class has to compare prevProps.roomId with this.props.roomId inside componentDidUpdate, disconnect the old room and connect the new one. The effect states it once: connect to roomId, and the cleanup disconnects. Nothing else is needed when roomId changes.

In development, StrictMode mounts, unmounts and mounts a component once more on purpose. This exposes effects whose cleanup is missing or wrong. It does not happen in production.

This is the class version of the same logic, for comparison:

jsx
import { Component } from 'react';

export default class ChatRoomClass extends Component {
  componentDidMount() {
    console.log('connect', this.props.roomId);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.roomId !== this.props.roomId) {
      console.log('disconnect', prevProps.roomId);
      console.log('connect', this.props.roomId);
    }
  }

  componentWillUnmount() {
    console.log('disconnect', this.props.roomId);
  }

  render() {
    return <h2>Room: {this.props.roomId}</h2>;
  }
}
jsx
import { useEffect, useState } from 'react';

function ChatRoom({ roomId }) {
  useEffect(() => {
    console.log('connect ' + roomId);
    return () => {
      console.log('disconnect ' + roomId);
    };
  }, [roomId]);

  return <h2>Room: {roomId}</h2>;
}

export default function App() {
  const [roomId, setRoomId] = useState('general');
  return (
    <>
      <button onClick={() => setRoomId('music')}>Join music</button>
      <ChatRoom roomId={roomId} />
    </>
  );
}

Console output after mounting and then clicking the button once (StrictMode is not used here, so there is no extra development cycle): connect general disconnect general connect music disconnect music

Key points

  • componentDidMount, componentDidUpdate and componentWillUnmount map roughly to one effect with its dependencies and cleanup.
  • Cleanup runs before the next effect run as well as on unmount.
  • The dependency array lists every reactive value the effect reads. It is not a way to say "run once".
  • StrictMode runs an extra mount-unmount-mount cycle in development to reveal missing cleanup.
  • Use an effect only to synchronise with an outside system. Derived values belong in render.

Common mistakes

  • Using an empty dependency array and reading props or state inside, which freezes stale values.
  • Forgetting cleanup for subscriptions, timers and listeners, which leaks memory and doubles callbacks.
  • Treating the StrictMode double mount as a bug and removing the cleanup that revealed it.
  • Computing derived data in an effect and storing it in state when it could be calculated during render.

Follow-ups

  • What happens when the dependency array is omitted entirely?
  • Why is "run once on mount" the wrong way to think about useEffect?
  • Which class lifecycle method has no direct hook equivalent, and what do you use instead?

Tips

  • Show the mapping first, then say why it is only approximate. That shows you understand effects instead of memorizing a table.
  • Use a connect and disconnect example. It makes the cleanup order obvious.
  • Mention StrictMode, since interviewers like to ask why effects fire twice in development.