Advanced React 04 · Techniques🔓 free after sign-in
Performance and rendering
When a component re-renders, memo, useMemo, useCallback, useTransition, useDeferredValue.
Loading lesson…
Advanced React 04 · Techniques🔓 free after sign-in
When a component re-renders, memo, useMemo, useCallback, useTransition, useDeferredValue.
Loading lesson…
Most React apps are fast without any extra work. But one day you'll run into this: a page with a note and a big chart, and when you type into the note, the letters appear with a delay.
function Dashboard() {const [note, setNote] = useState('') // the note's textreturn (<><input value={note} onChange={(e) => setNote(e.target.value)} /><ExpensiveChart year={2025} /> {/* a made-up component: a chart whose calculation takes 150 ms */}</>)}
What happens on every letter:
note state in Dashboard (lesson React basics 03).Dashboard() again – and with it ExpensiveChart(), even though the chart didn't change at all.The chart has nothing to do with the note, yet it slows it down. This lesson is about how to find such a place and remove it – first by changing the structure, and only when that isn't enough with the tools memo, useMemo, useCallback, useDeferredValue and useTransition.
Back to the kitchen. The head chef (a parent component) has helpers (child components). Whenever the head chef changes their recipe, all the helpers go through their recipes again and check whether their plate still matches. Mostly they find it does and change nothing. Going through a recipe like that is called a render. Going through a recipe is quick; what's expensive is actually swapping a plate on the table – and React does that only where the result differs. The trouble starts when one helper has a lot of work and the others have to wait for them.
A simple rule: only once something is slow, not in advance. The table shows typical symptoms; the usual cause is in the middle, the tool and section on the right:
| Symptom | Usual cause | What to try |
|---|---|---|
| nothing is slow | — | nothing – don’t add memo "just in case" |
| typing into a field stutters because of an expensive part next to it | the state is higher than it needs to be | move state down, children (section 2) |
| an expensive component re-renders with the same props | the parent re-renders often | memo + stable props (section 3) |
| a field reacts slowly above a big list of results | the list is calculated on every letter | useDeferredValue (section 4) |
| switching a tab freezes the page for a moment | the new tab is slow | useTransition (section 4) |
| thousands of rows | even what isn’t visible is rendered | virtualisation (section 5) |
A component renders (React calls its function) when:
Point 2 surprises people the most. Let's take the Dashboard from the introduction apart once more:
note state in Dashboard changes.Dashboard(). It returns JSX with <ExpensiveChart year={2025} />.ExpensiveChart() too – even though year is still 2025. React doesn't compare props on its own. The head chef changed the recipe, so the helper has to go through theirs.Two techniques that speed up an app without a single memo. Both build on the fact that what re-renders is the component with the changed state and everything under it – nothing above it or next to it.
In the example above, only the input needs note. The chart knows nothing about it. So why is the state in a component that also contains the chart? Let's move it into a separate component:
function Dashboard() {return (<><NoteInput /> {/* the note state is inside */}<ExpensiveChart year={2025} /></>)}function NoteInput() {const [note, setNote] = useState('')return <input value={note} onChange={(e) => setNote(e.target.value)} />}
Now a change of note re-renders only NoteInput. Neither Dashboard nor the chart finds out anything – the salt changed in just one sauce.
What if the state has to be in the wrapping component – a background colour used by the wrapper around the chart, say? Then the children trick helps:
// ❌ ColorPicker creates the chart itself → re-renders it when the colour changesfunction ColorPicker() {const [color, setColor] = useState('white')return (<div style={{ background: color }}><input type="color" onChange={(e) => setColor(e.target.value)} /> {/* type="color" = a colour picker */}<ExpensiveChart year={2025} /></div>)}// ✅ The parent creates the chart and passes it as childrenfunction ColorPicker({ children }: { children: ReactNode }) {const [color, setColor] = useState('white')return (<div style={{ background: color }}><input type="color" onChange={(e) => setColor(e.target.value)} />{children}</div>)}<ColorPicker><ExpensiveChart year={2025} /></ColorPicker>
Why does it work? The <ExpensiveChart /> element is now created in ColorPicker's parent. When the colour changes, React re-renders ColorPicker, but children is still the same element as before – nobody created it again. React sees it hasn't changed and skips the chart. A finished dish brought in from another kitchen doesn't get cooked again.
When organising isn't enough, it's time for a helper who looks at the order before working: "Is it the same as last time? Then I do nothing and hand over the previous plate." That's memo.
const ExpensiveChart = memo(function ExpensiveChart({ year }: { year: number }) {// …an expensive calculation…})
memo is a function that takes a component and returns its guarded version. The guarded version remembers the props from the last render. When the parent renders again, it compares the new props with the old ones one by one – and when they're all the same, it skips the render and reuses the last result.
There's a catch, though. The helper doesn't compare orders by content, but by whether it's the same slip of paper – it compares like === (precisely with Object.is, from JavaScript 09). For numbers and text that's the same thing: 2025 === 2025 is true. But two objects with the same content aren't equal: { a: 1 } === { a: 1 } is false, because they're two different objects in memory. And objects and functions written in a component's body are created anew on every render of the parent – it's a new slip, even though the same thing is written on it:
function Dashboard() {const [note, setNote] = useState('')// A NEW object and a NEW function on every renderconst options = { year: 2025, color: 'blue' }const handleClick = (point: Point) => console.log(point) // Point = the chart point that was clickedreturn (<><input value={note} onChange={(e) => setNote(e.target.value)} /> {/* every letter = a new render of Dashboard */}<ExpensiveChart options={options} onPointClick={handleClick} /></>)// memo compares: options === the previous options? NO → re-renders anyway}
The solution is to remember those values, so the parent hands over the same slip on the next render:
// inside Dashboard above – instead of the two lines with options and handleClickconst options = useMemo(() => ({ year: 2025, color: 'blue' }), []) // the same objectconst handleClick = useCallback((point: Point) => console.log(point), []) // the same function
You know both hooks from lesson Hooks 04 ("A stable context value"), where they kept the context value the same so its listeners didn't re-render. Here they solve the same problem for memo. A reminder:
useMemo(calculation, dependencies) returns the remembered result of the calculation function until one of the dependencies changes. useCallback(fn, dependencies) does the same with a function – it's just a shorter way of writing useMemo(() => fn, dependencies).[] means "depends on nothing" – the object and the function are created once and stay the same from then on.() => ({ year: 2025, color: 'blue' }) are needed because the arrow returns an object – without them JavaScript would read the curly braces as the function's body (JavaScript 02).A common question: when options holds fixed values and the dependencies are empty, why not just a constant outside the component, const options = { year: 2025, color: 'blue' } above Dashboard, outside it? That would work too – it's created once when the file loads and stays the same object. useMemo is needed only when the object or function uses something from the component (state, props), because outside the component you can't reach it. That's the very next example. And handleClick would typically call a state setter in a real app, which is why it stays inside.
Dependencies are written just like for an effect: every value from the component that the function inside uses. When the object depends on the year state, year goes into the array – otherwise useMemo would remember the old year forever:
// inside a component, above returnconst [year, setYear] = useState(2025)const options = useMemo(() => ({ year, color: 'blue' }), [year])// year hasn't changed → the same object; year has changed → a new object with the new year
useMemo has a second use too: it saves an expensive calculation. When a component filters a big list, it doesn't have to filter it again on every render, only when the list or the query changes:
// inside a component with a task list (todos and query are its state or props), above return// without useMemo: filters on EVERY render, even when something else entirely changedconst visible = todos.filter((t) => t.text.includes(query))// with useMemo: filters only when todos or query change; otherwise returns the last resultconst visible = useMemo(() => todos.filter((t) => t.text.includes(query)), [todos, query])
The table sums up all three tools; each row says what the tool does and when to use it:
| Tool | What it does | When to use it |
|---|---|---|
memo(Comp) | Skips the render when all props are the same (by reference). | An expensive component that often re-renders with the same props. |
useMemo(fn, deps) | Remembers the RESULT of a calculation. | An expensive calculation; or a stable object/array for a memo component or an effect dependency. |
useCallback(fn, deps) | Remembers a FUNCTION (= useMemo(() => fn)). | A function passed to a memo component or used in an effect’s dependencies. |
What you see: A parent with a counter and four child cards. A card flashes yellow when it renders. The cards differ in whether they're wrapped in memo and what props they get.
Try it:
memo. It gets a style object and a function created right in the render – a new slip every time.useMemo and useCallback. It doesn't flash.The takeaway: memo helps only when the props really are the same references. A single object or function created in the render knocks it out.
Loading the interactive part…
In a restaurant, the guest who has just walked in comes first – you have to greet them right away. Polishing the cutlery can wait, and when another guest walks in while you're doing it, you stop polishing and come back to it later.
React can do the same. Some updates are urgent – typing into a field, a click; the user expects an immediate response. Others are non-urgent – re-rendering a big list of results. React can start a non-urgent render and, when an urgent one comes, interrupt it and come back to it later. You just have to tell it which is which.
function Search() {const [query, setQuery] = useState('')const deferredQuery = useDeferredValue(query) // "a delayed copy"return (<><input value={query} onChange={(e) => setQuery(e.target.value)} /><SlowList query={deferredQuery} /></>)}const SlowList = memo(function SlowList({ query }: { query: string }) { … })
useDeferredValue(query) returns a value that lags a moment behind query. In the quick render after a key press it still returns the old one; it returns the new one only in the next, slower render, which React starts by itself as soon as it has time. So the input gets the fresh query and the slow list the deferred deferredQuery.
What happens when you type the letter "a":
query is "a", but deferredQuery is still the old value "". The input shows "a" at once. SlowList gets the same prop as last time and thanks to memo is skipped.deferredQuery is "a" too – now SlowList gets calculated.What you see: A field and under it a list of 400 artificially slowed-down items (each render of the list takes about 120 ms). The checkbox switches useDeferredValue on. When the list shows a stale value, it fades.
Try it:
The takeaway: The slow list still takes just as long. But it no longer blocks typing – React calculates it "between the letters" and interrupts it.
Loading the interactive part…
When you have access to the setter, you can mark a non-urgent change directly. Typically switching tabs: the click responds at once, but rendering the content of a slow tab can wait – and if you click another tab in the meantime, React throws away the half-done work.
type Tab = 'about' | 'posts' | 'contact' // the tab namesconst [tab, setTab] = useState<Tab>('about')const [isPending, startTransition] = useTransition()function selectTab(next: Tab) {startTransition(() => setTab(next)) // this change is non-urgent}// in the JSX: <button onClick={() => selectTab('posts')}>Posts</button>{isPending && <Spinner />} // while the new tab is being calculated (Spinner = a spinning loading icon)
useTransition() returns an array with two things, which you unpack just like with useState:
startTransition – a function you pass another function to. React treats every state change inside it as non-urgent: it starts calculating it in the background and interrupts it when something more pressing comes.isPending – true while the non-urgent change is being calculated. Use it to show that something is happening.What you see: Three tabs. "Posts" is artificially slow (its render takes about 300 ms). The checkbox switches useTransition on.
Try it:
The takeaway: A transition turns a slow switch into interruptible background work. The user can keep clicking and sees that something is happening.
Loading the interactive part…
Both hooks do the same thing – mark work as non-urgent – just from a different side. The table compares them row by row. In the last row: with useDeferredValue you can tell it's waiting because the deferred value still differs from the fresh one.
| useTransition | useDeferredValue | |
|---|---|---|
| What you wrap | A state update (setX) | A value |
| When | You have access to the setter (switching tabs, navigation) | The value comes from outside (props), or you want the field immediately and the list later |
| How you tell it’s waiting | isPending | value !== deferredValue |
A list has 10,000 rows, but twenty fit in the window. Without virtualisation React creates all 10,000 elements – and every render goes through them. Virtualisation renders only the twenty visible ones (plus a few above and below the window). When the user scrolls, rows that left the window are removed and new ones are added. The user notices nothing, but React works with twenty rows instead of ten thousand – no need to polish cutlery nobody can see. You don't have to write it yourself: ready-made libraries are TanStack Virtual or react-window. For hundreds of rows you usually don't need virtualisation; for thousands you do.
At build time the app is packed into JavaScript files that the browser downloads. When they include a heavy chart most visitors never open, everyone downloads it for nothing. Code splitting puts such a component into a separate file that's downloaded only when it's needed. This course does it with every lesson.
import { lazy, Suspense } from 'react'// 1. lazy: a component whose code is downloaded only when it's first renderedconst Chart = lazy(() => import('./Chart'))// 2. Suspense: what to show while the code downloads (fallback = stand-in content)<Suspense fallback={<Spinner />}>{showChart && <Chart data={data} />}</Suspense>
import('./Chart') is the dynamic import from JavaScript 08: the module isn't loaded at the start but only when that line runs, and it returns a Promise. Vite (the tool that builds the project) turns such a module into a separate file.lazy gets a function that starts the import and returns a component. You use it like any other. When React renders it for the first time, it calls the function and the file starts downloading.Suspense around it shows the fallback – say, a spinner. As soon as the code is downloaded, it replaces it with the real chart. More about Suspense in Advanced React 08.This section puts the lesson together into steps to come back to when something is slow. You'll find the same pattern in the Cheat sheets on the React tab.
children.memo and stabilise the objects and functions you send it with useMemo and useCallback.useDeferredValue for a value, useTransition for a state change.// the file src/pages/Dashboard.tsx – steps 2 to 4 of the procedure in one fileimport { memo, useCallback, useDeferredValue, useMemo, useState, useTransition } from 'react'interface Point { x: number; y: number } // a point of the chartinterface ChartProps {options: { year: number; color: string } // the chart's settings (an object)onPick: (point: Point) => void // called after a click on a point}// ─── 2. ORGANISE: state only where it's needed ──────────────function NoteBox() {const [note, setNote] = useState('') // typing re-renders only NoteBoxreturn <input value={note} onChange={(e) => setNote(e.target.value)} />}// ─── 3. MEMOISE: an expensive component in memo ─────────────// memo skips the render when all props are the same (===) as last timeconst ExpensiveChart = memo(function ExpensiveChart({ options, onPick }: ChartProps) {// …an expensive calculation and drawing of the chart; after a click on a point it calls onPick(point)return <div>Chart for {options.year}</div>})// ─── 4. DEFER: a slow list (in memo too – otherwise deferring wouldn't help)const SlowList = memo(function SlowList({ query }: { query: string }) {// …expensive filtering and drawing of a big list by queryreturn <ul>{/* results for query */}</ul>})type Tab = 'chart' | 'list' // the tab namesexport function Dashboard() {const [year, setYear] = useState(2025)const [selected, setSelected] = useState<Point | null>(null) // the selected point of the chartconst [query, setQuery] = useState('') // the search textconst [tab, setTab] = useState<Tab>('chart') // the open tab// 3. stable props for memo: the same object and the same function until the dependencies changeconst options = useMemo(() => ({ year, color: 'blue' }), [year]) // a new object only when year changesconst onPick = useCallback((point: Point) => setSelected(point), []) // the setter never changes → []// 4. the field gets query at once, the slow list a deferred copyconst deferredQuery = useDeferredValue(query)// switching a tab is non-urgent; isPending = the new tab is still being computedconst [isPending, startTransition] = useTransition()return (<><NoteBox /><button onClick={() => setYear((y) => y - 1)}>Previous year</button>{selected && <p>Selected point: {selected.x}, {selected.y}</p>}<button onClick={() => startTransition(() => setTab('chart'))}>Chart</button><button onClick={() => startTransition(() => setTab('list'))}>List</button>{isPending && <p>Loading the tab…</p>}{tab === 'chart' && <ExpensiveChart options={options} onPick={onPick} />}{tab === 'list' && (<><input value={query} onChange={(e) => setQuery(e.target.value)} /><SlowList query={deferredQuery} /></>)}</>)}
memo doesn't get objects or functions created right in render.useDeferredValue targets a component in memo.Try typing into the note and watch the price flash. One wrap stops it.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The first challenge is exactly the example from the introduction and sections 1–3: fix it first by organising the kitchen, then by memoising, and compare the two solutions. The second practises section 4 – the field must react immediately, even though the list takes longer to calculate. For each, first ask the three questions from the introduction: what is slow, why it re-renders and whether it must happen right now.
Find out why typing is slow and fix it – first with structure, then with memoisation. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
The guest at the door (typing) comes before polishing the cutlery (the list of results). What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
children.useMemo/useCallback.useRenderFlash)useRenderFlash – from the file src/course/useRenderFlash.ts. A teaching helper hook: the element flashes on every render so you can see what re-renders. You won't need it in your own code./*** A teaching helper hook: the element briefly "flashes" after every render of the component.* An effect without a dependency array runs after every commit – exactly what we want to visualize.*/export function useRenderFlash<T extends HTMLElement>() {const ref = useRef<T>(null)useEffect(() => {const el = ref.currentif (!el) returnel.classList.remove('flash')void el.offsetWidth // restart the CSS animationel.classList.add('flash')})return ref}
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).