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 method | Hook equivalent |
|---|---|
componentDidMount | useEffect(() => { ... }, []) |
componentDidUpdate (for specific values) | useEffect(() => { ... }, [value]) |
componentWillUnmount | the cleanup returned from an effect |
shouldComponentUpdate | React.memo (or the React Compiler) |
getSnapshotBeforeUpdate | useLayoutEffect reading the DOM |
componentDidCatch | no hook; use a class error boundary or a library |
getDerivedStateFromProps | compute during render, or adjust state during render with a guard |
Differences to remember
- Effects run after paint;
componentDidMountran before paint. For measurements that must happen before paint, useuseLayoutEffect. componentDidUpdatedoes 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";23export function Lifecycle({ userId }: { userId: string }) {4 const [width, setWidth] = useState(0);5 const boxRef = useRef<HTMLDivElement>(null);67 // componentDidMount + componentWillUnmount8 useEffect(() => {9 const onKey = (e: KeyboardEvent) => e.key === "Escape" && console.log("escape");10 window.addEventListener("keydown", onKey);11 return () => window.removeEventListener("keydown", onKey);12 }, []);1314 // componentDidUpdate for userId (also runs on mount)15 useEffect(() => {16 console.log("load data for", userId);17 }, [userId]);1819 // getSnapshotBeforeUpdate-style: measure before the browser paints20 useLayoutEffect(() => {21 setWidth(boxRef.current?.getBoundingClientRect().width ?? 0);22 }, [userId]);2324 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.