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
constructor(props): initialize state (or use class fields).static getDerivedStateFromProps(props, state): rare; sync state with props before render.render(): return JSX; must be pure.componentDidMount(): after insertion into the DOM. Fetch data, subscribe, measure.
Updating
getDerivedStateFromPropsagain.shouldComponentUpdate(nextProps, nextState): returnfalseto skip rendering (or extendPureComponent).render().getSnapshotBeforeUpdate(prevProps, prevState): read DOM info (like scroll position) right before changes apply.componentDidUpdate(prevProps, prevState, snapshot): react to changes; compare with previous values before callingsetStateto 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
1import { Component, createRef } from "react";23type Props = { messages: string[] };45export class ChatLog extends Component<Props> {6 private listRef = createRef<HTMLUListElement>();78 componentDidMount() {9 window.addEventListener("resize", this.onResize);10 }1112 getSnapshotBeforeUpdate(prev: Props) {13 // Capture whether the user was scrolled to the bottom before new messages render14 const el = this.listRef.current!;15 return prev.messages.length < this.props.messages.length16 ? el.scrollHeight - el.scrollTop - el.clientHeight < 1017 : null;18 }1920 componentDidUpdate(_prev: Props, _state: unknown, wasAtBottom: boolean | null) {21 if (wasAtBottom) this.listRef.current!.scrollTop = this.listRef.current!.scrollHeight;22 }2324 componentWillUnmount() {25 window.removeEventListener("resize", this.onResize);26 }2728 onResize = () => console.log("resized");2930 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.