ReactMedium

What are the common lifecycle methods in class components?

The common class lifecycle methods are constructor, render, componentDidMount, componentDidUpdate, componentWillUnmount and shouldComponentUpdate, plus the less common getDerivedStateFromProps, getSnapshotBeforeUpdate, and the error boundary methods getDerivedStateFromError and componentDidCatch.

Mounting

  1. constructor(props): initialize state (or use class fields).
  2. static getDerivedStateFromProps(props, state): rare; sync state with props before render.
  3. render(): return JSX; must be pure.
  4. componentDidMount(): after insertion into the DOM. Fetch data, subscribe, measure.

Updating

  1. getDerivedStateFromProps again.
  2. shouldComponentUpdate(nextProps, nextState): return false to skip rendering (or extend PureComponent).
  3. render().
  4. getSnapshotBeforeUpdate(prevProps, prevState): read DOM info (like scroll position) right before changes apply.
  5. componentDidUpdate(prevProps, prevState, snapshot): react to changes; compare with previous values before calling setState to avoid loops.

Unmounting

componentWillUnmount(): remove listeners, cancel timers and requests.

Error handling

static getDerivedStateFromError(error) and componentDidCatch(error, info) make the component an error boundary. This is the main reason classes are still written today.

Removed or legacy

componentWillMount, componentWillReceiveProps and componentWillUpdate are legacy (UNSAFE_ prefixed). String refs and legacy context were removed in React 19.

Hook equivalents

componentDidMount/DidUpdate/WillUnmount map to useEffect; shouldComponentUpdate to React.memo; getSnapshotBeforeUpdate to useLayoutEffect.

Code example

tsx
1import { Component, createRef } from "react";
2
3type Props = { messages: string[] };
4
5export class ChatLog extends Component<Props> {
6 private listRef = createRef<HTMLUListElement>();
7
8 componentDidMount() {
9 window.addEventListener("resize", this.onResize);
10 }
11
12 getSnapshotBeforeUpdate(prev: Props) {
13 // Capture whether the user was scrolled to the bottom before new messages render
14 const el = this.listRef.current!;
15 return prev.messages.length < this.props.messages.length
16 ? el.scrollHeight - el.scrollTop - el.clientHeight < 10
17 : null;
18 }
19
20 componentDidUpdate(_prev: Props, _state: unknown, wasAtBottom: boolean | null) {
21 if (wasAtBottom) this.listRef.current!.scrollTop = this.listRef.current!.scrollHeight;
22 }
23
24 componentWillUnmount() {
25 window.removeEventListener("resize", this.onResize);
26 }
27
28 onResize = () => console.log("resized");
29
30 render() {
31 return <ul ref={this.listRef} style={{ maxHeight: 200, overflow: "auto" }}>
32 {this.props.messages.map((m, i) => <li key={i}>{m}</li>)}
33 </ul>;
34 }
35}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app