Keep a slow calculation from running on every render. Toggle the theme and it is skipped; change n and it runs.
React · intermediate · 7 min · 28 steps · free
import { useMemo, useState } from 'react';
function slowSquare(n) {
console.log(`calculating ${n}²`);
return n * n;
}
export default function Calculator() {
const [n, setN] = useState(4);
const [dark, setDark] = useState(false);
const square = useMemo(() => slowSquare(n), [n]);
return (
<div className={dark ? 'dark' : 'light'}>
<p>{n}² = {square}</p>
<button onClick={() => setDark(!dark)}>Toggle theme</button>
<button onClick={() => setN(n + 1)}>n + 1</button>
</div>
);
}<Calculator> for the first time: it calls the Calculator function.useState runs for the first time, so React stores the starting value for n and returns it: 4.useState runs for the first time, so React stores the starting value for dark and returns it: false.slowSquare returns 16.useMemo gives square = 16. It only recalculates when a dependency changes.Calculator returns JSX: a description of what the screen should show, <div className="light">…</div>. React has not changed the page yet.dark changes.setDark(!dark) does not change dark right away: React queues the update and will render again. In this call dark is still false.<Calculator> again (render 2): it calls Calculator once more, from the top.useState returns the value React has kept for n: 4. The starting value is only used on the first render.useState returns the value React has kept for dark: true. The starting value is only used on the first render.Calculator returns JSX: a description of what the screen should show, <div className="dark">…</div>. React has not changed the page yet.setN(n + 1) does not change n right away: React queues the update and will render again. In this call n is still 4.<Calculator> again (render 3): it calls Calculator once more, from the top.useState returns the value React has kept for n: 5. The starting value is only used on the first render.useState returns the value React has kept for dark: true. The starting value is only used on the first render.slowSquare returns 25.useMemo gives square = 25. It only recalculates when a dependency changes.Calculator returns JSX: a description of what the screen should show, <div className="dark">…</div>. React has not changed the page yet.Answer: When a changes
Answer: The value. useCallback returns the function.
← memo: Skipping a Re-render · useCallback with memo →