All topics
Advancedintermediate

Class Components and Legacy Lifecycle Methods

Understand class component lifecycle methods for maintaining legacy codebases, and how they map conceptually to hooks.

Before hooks, all stateful React components were written as classes extending React.Component, using named lifecycle methods to hook into the mount/update/unmount phases: componentDidMount (runs once after the initial render, commonly used for data fetching or subscriptions), componentDidUpdate(prevProps, prevState) (runs after every re-render, given the previous props/state for comparison), and componentWillUnmount (runs just before the component is removed, for cleanup).

Class lifecycle methods are like named stops on a scheduled train route — 'arrival' (componentDidMount), 'in-transit adjustments' (componentDidUpdate), and 'final departure' (componentWillUnmount) — each a fixed, separately named station, whereas hooks-based effects are more like a standing instruction to 'keep this thing synchronized with these specific conditions,' regardless of which named phase of the journey it happens to correspond to.

Key Concepts

1
State in a class component lives on this.state, an object updated exclusively via this.setState(partialState), which shallow-merges the given partial object into the existing state rather than replacing it outright — a meaningfully different default behavior from useState's setter, which replaces the state value entirely unless you manually spread the previous value yourself.
this.statethis.setState(partialState)useState
2
While virtually all new React code today is written with function components and hooks, understanding class lifecycle methods remains relevant for maintaining legacy codebases, and because Error Boundaries (see that topic) currently still require a class component, since their required lifecycle methods (getDerivedStateFromError, componentDidCatch) have no hook equivalent.
getDerivedStateFromErrorcomponentDidCatch
3
Interviewers occasionally ask candidates to translate a class component's componentDidMount + componentDidUpdate + componentWillUnmount trio into an equivalent function component using a single useEffect, testing whether they understand the conceptual mapping (and its imperfect edges) between named lifecycle phases and the dependency-array-driven synchronization model hooks use instead.
componentDidMountcomponentDidUpdatecomponentWillUnmountuseEffect