Sikau

React · Day 19 · about 30 min

Performance: memo and useMemo

Skip work that doesn't need redoing.

Re-render everything?

When state changes, React re-renders that component and all its children. Usually that's fast enough. When it isn't — a huge list, an expensive calculation — memoization lets React reuse earlier work.

Measure first (React DevTools Profiler). Most apps never need these tools — and the React Compiler can add them automatically.

memo, useMemo, useCallback

import { memo, useMemo, useState } from "react";

const Row = memo(function Row({ name }) {
  console.log("render", name);
  return <li>{name}</li>;
});

const NAMES = ["Asha", "Bikash", "Chandra"];

export default function List() {
  const [count, setCount] = useState(0);
  const [filter, setFilter] = useState("");
  const shown = useMemo(() => NAMES.filter((n) => n.toLowerCase().includes(filter)), [filter]);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Clicked {count}</button>
      <input value={filter} onChange={(e) => setFilter(e.target.value)} />
      <ul>{shown.map((n) => <Row key={n} name={n} />)}</ul>
    </div>
  );
}
  • useCallback(fn, deps) keeps the same function between renders — useful when passing callbacks to memo'd children.
  • Objects and arrays created during render are new every time, which defeats memo — memoize them or pass simpler props.
  • Bigger wins usually come from rendering less: pagination, virtualised lists, moving state down closer to where it's used.

The rest of this lesson

  • When re-renders are actually slowexplain
  • Cheaper than memoisingexplain
  • Does Row re-render?predict
  • Pick the toolmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React