React / 44
From lifecycle methods to hooks
Most lifecycle methods fold into one useEffect with a cleanup. Plus the classic question, why the useEffect callback can't be async, and the fix.
The lookup table
constructor + this.stateuseState(initial)expensive start value: useState(() => calc())
componentDidMountuseEffect(fn, [])runs once after the first paint
componentDidUpdateuseEffect(fn, [dep])runs after mount too, then when dep changes
componentWillUnmountreturn () => cleanupthe cleanup returned by the same effect
this.setState(partial)setX(next)replaces, doesn't merge
this.timerId (instance field)useRef()a box that survives renders, no re-render
PureComponent / shouldComponentUpdatememo(Component)skip re-render when props are equal
static contextTypeuseContext(Ctx) / use(Ctx)read context
getDerivedStateFromError · componentDidCatchno hookerror boundaries are still classes
getSnapshotBeforeUpdateno hookrare; stays a class
The big idea: in a class, setup and teardown live in separate methods (componentDidMount, componentWillUnmount), and "redo it when something changes" lives in a third (componentDidUpdate). In a function, they live together in one effect.
class Clock extends Component {
state = { now: new Date() };
componentDidMount() {
this.timerId = setInterval(() => {
this.setState({ now: new Date() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return <p>{this.state.now.toLocaleTimeString()}</p>;
}
}import { useEffect, useState } from "react";
function Clock() {
const [now, setNow] = useState(new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id); // cleanup
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}Setup and its undo now sit side by side, so it's much harder to forget one. The timer id is a plain local variable instead of this.timerId.
Think "sync", not "lifecycle"
useEffect(fn, [userId]) isn't really "didMount plus didUpdate". It means "keep this in sync with userId": run after mount, and whenever userId changes, first clean up the old run, then run again. That one rule replaces the prevProps.userId !== this.props.userId check you wrote by hand in a class.
Two timing differences worth knowing:
componentDidMountruns before the browser paints.useEffectusually runs after paint, so it doesn't block the screen. For the rare case where you must measure or adjust the DOM before the user sees it, useuseLayoutEffect.- An effect with dependencies also runs on mount;
componentDidUpdatenever does.
Why the effect callback can't be async
In a class, React ignores whatever componentDidMount returns, so async componentDidMount() works fine. useEffect is different: its return value means something. React keeps it and calls it later as the cleanup.
the contract
useEffect(() => { … return cleanup })allowed returns
a function: React calls it before the next run and on unmount
nothing (undefined): no cleanup needed
the mistake
useEffect(async () => { await … })what react gets
Promise { <pending> }a console warning on mount
TypeError: destroy is not a function when React tries to clean up
An async function always returns a Promise, even with no return statement. So React receives a Promise where it expected a function or nothing. React 19 warns in the console on mount, and when it later tries to run the "cleanup" (on unmount or when dependencies change), it calls the Promise and throws TypeError: destroy is not a function.
Don't
An async effect callback
useEffect(async () => {
const res = await fetch(url);
setRecipes((await res.json()).recipes);
}, [url]);Do
An async function inside the effect
useEffect(() => {
let ignore = false;
async function load() {
const res = await fetch(url);
const data = await res.json();
if (!ignore) setRecipes(data.recipes);
}
load();
return () => {
ignore = true; // a stale reply is ignored
};
}, [url]);With url = "https://dummyjson.com/recipes?limit=5", that loads five recipes. The ignore flag does the same job as the id === this.props.userId check in the class version: if url changes before the reply arrives, the old reply is thrown away. The effect still returns a proper cleanup function, so React is happy.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
