ReactEasy

Equivalent of lifecycle methods in useEffect?

useEffect(fn, []) behaves like componentDidMount (with its cleanup as componentWillUnmount), useEffect(fn, [deps]) like componentDidUpdate for those values, and the returned cleanup function runs before each re-run and on unmount. But effects are better understood as synchronization with external systems than as lifecycle events.

Mapping

Class methodHook equivalent
componentDidMountuseEffect(() => { ... }, [])
componentDidUpdate (for specific values)useEffect(() => { ... }, [value])
componentWillUnmountthe cleanup returned from an effect
shouldComponentUpdateReact.memo (or the React Compiler)
getSnapshotBeforeUpdateuseLayoutEffect reading the DOM
componentDidCatchno hook; use a class error boundary or a library
getDerivedStateFromPropscompute during render, or adjust state during render with a guard

Differences to remember

  • Effects run after paint; componentDidMount ran before paint. For measurements that must happen before paint, use useLayoutEffect.
  • componentDidUpdate does not run on mount; useEffect([value]) does. Use a ref to skip the first run if necessary (rarely needed).
  • Each effect handles one concern with its own setup and cleanup, instead of mixing concerns in one lifecycle method.
  • Effects capture props and state from their render (closures), so dependencies must be listed.

Strict Mode

React runs mount, unmount, mount in development; a correct cleanup makes this invisible.

Code example

tsx
1import { useEffect, useLayoutEffect, useRef, useState } from "react";
2
3export function Lifecycle({ userId }: { userId: string }) {
4 const [width, setWidth] = useState(0);
5 const boxRef = useRef<HTMLDivElement>(null);
6
7 // componentDidMount + componentWillUnmount
8 useEffect(() => {
9 const onKey = (e: KeyboardEvent) => e.key === "Escape" && console.log("escape");
10 window.addEventListener("keydown", onKey);
11 return () => window.removeEventListener("keydown", onKey);
12 }, []);
13
14 // componentDidUpdate for userId (also runs on mount)
15 useEffect(() => {
16 console.log("load data for", userId);
17 }, [userId]);
18
19 // getSnapshotBeforeUpdate-style: measure before the browser paints
20 useLayoutEffect(() => {
21 setWidth(boxRef.current?.getBoundingClientRect().width ?? 0);
22 }, [userId]);
23
24 return <div ref={boxRef}>User {userId}, box width {width}px</div>;
25}

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