Skip to content
ClapelloNotes by Barath
ReactCh 08 · 5/6
Core4 min readUpdated

React / 44

From lifecycle methods to hooks

TL;DR

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.state
useState(initial)

expensive start value: useState(() => calc())

componentDidMount
useEffect(fn, [])

runs once after the first paint

componentDidUpdate
useEffect(fn, [dep])

runs after mount too, then when dep changes

componentWillUnmount
return () => cleanup

the 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 / shouldComponentUpdate
memo(Component)

skip re-render when props are equal

static contextType
useContext(Ctx) / use(Ctx)

read context

getDerivedStateFromError · componentDidCatch
no hook

error boundaries are still classes

getSnapshotBeforeUpdate
no hook

rare; stays a class

Most lifecycle methods fold into one useEffect: setup in the body, teardown in the returned function. Error boundaries have no hook version.

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:

  • componentDidMount runs before the browser paints. useEffect usually 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, use useLayoutEffect.
  • An effect with dependencies also runs on mount; componentDidUpdate never 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 })
React stores the return value

allowed returns

a function: React calls it before the next run and on unmount

nothing (undefined): no cleanup needed

the mistake

useEffect(async () => { await … })
async always returns a Promise

what react gets

Promise { <pending> }

a console warning on mount

TypeError: destroy is not a function when React tries to clean up

React keeps whatever your effect returns and calls it later as the cleanup. An async function always returns a Promise, and a Promise can't be called.

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.