A GST invoice ledger shows thousands of rows, and a slow keystroke in it has to be traced to a step. React turns state into pixels in three steps, and every performance question in this chapter is a question about one of them.
React's own guide names them trigger, render and commit. A trigger is a request for a render. There are two: the first render, when createRoot(...).render() runs, and a state update, when a setter is called. Render means React calls your components to work out what the screen should show. Commit means React applies the difference to the DOM. After the commit, the browser paints, which means drawing the changed pixels. React's guide uses the word painting for that last step to keep it apart from rendering.
Rendering is only calculation. A component that renders produces a description, and nothing on the page changes until commit. Rendering is also recursive: when a component renders, React renders the components it returns, and so on down the tree. That is why a state change near the top of a big tree can mean thousands of component calls.
The order of calls
Components render top down, parent before child. Effects run after commit, in the opposite direction: a child's effect runs before its parent's. There are two kinds. A layout effect is one React runs before the browser paints, and a passive effect, the ordinary useEffect, is allowed to run after the paint. The react.dev reference says React guarantees layout effects and any updates they schedule are processed before the repaint.
The lab below logs every step. Each Row has both kinds of effect with no dependency array, so they run after every render, and each effect logs its cleanup too.
The test mounts the ledger, then clicks the button to add a third row.
text
mount:
render Ledger
render Row a
render Row b
layout setup Row a
layout setup Row b
effect setup Row a
effect setup Row b
effect setup Ledger
after a click on add:
render Ledger
render Row a
render Row b
render Row c
layout cleanup Row a
layout cleanup Row b
layout setup Row a
layout setup Row b
layout setup Row c
effect cleanup Row a
effect cleanup Row b
effect setup Row a
effect setup Row b
effect setup Row c
effect setup Ledger
Real run, React 19.3.1, StrictMode off.
On mount, the order was Ledger, Row a, Row b for renders, then both rows' layout setups, then both rows' passive setups, and last the Ledger's own passive setup, because a parent's effect follows its children's. On the click, all four renders came first, top down. Then every layout cleanup ran, then every layout setup, then every passive cleanup and every passive setup. A cleanup for an effect always runs before the next setup of that effect, and React runs all cleanups of one kind before any setups of that kind.
Animated sceneOne click through render, commit and effects0:21
Watch for the order of renders, the commit and the effects after one click
Read it as steps
Rows render top down, then the commit, then layout effects, then passive ones
What the picture adds
The scene shows the same click. Rows a and b rendered again although only a third row was added, because their parent rendered and they are ordinary components. The commit step then changed the page in one place only, the new list item, which follows react.dev's description: React applies the minimal changes and leaves the rest of the DOM alone. Rendering a component again is not the same as changing its DOM.
That distinction is the key to this whole chapter. A render that produces the same output costs time for the calls but changes nothing on screen, so it is a candidate for removal. A commit that changes many nodes costs layout and paint work, and is a candidate for reducing the node count.
jsdom, the DOM used by the tests, has no layout or paint, so it can show the order of renders and effects and nothing about paint. Timing that depends on the browser, including the numbers in the last lesson, comes from a real Chrome.
Check your understanding
What are the two triggers for a render?
The first render from createRoot(...).render(), and a state update from a setter. A re-rendered parent renders its children, but it is the state update that starts it.
In the log, why did effect setup Ledger come after the rows' effects?
Effects run child before parent, so a parent's effect follows the effects of the components below it.
Row a rendered again when row c was added. Did its DOM change?
No. Render only calculates the output. The commit changed only where the output differed, which was the new list item.
Part 2 · Reconciliation and component identity
Matching old and new
After a component renders, React compares the new output with the old one to decide what to change. This comparison is reconciliation. The process is a fast heuristic that checks the tree level by level, and its rules decide whether a piece of the screen keeps its state or starts again.
The rules, as React's guides state them, are short. If an element at a position has a different type from before, React throws away the old subtree and builds a new one, and any state inside is lost. If the type is the same, React keeps the existing instance and updates its props. Children are compared by position, unless they have keys. A key is a stable identity that tells React which child is which when a list changes. State lives with the component at a position in the tree, not with the JSX that describes it.
A component defined inside another
The most common way to break identity is to declare a component inside another component's body. Each time the outer component renders, the inner declaration creates a new function, and a new function is a new type. React sees a different type at that position and rebuilds everything below it.
The test types a GSTIN into the field, then clicks the button, which changes a counter in the parent.
text
defined inside: typed "29ABC", after a parent render ""
log: inner GstField mounted, inner GstField unmounted, inner
GstField mounted
defined outside: typed "29ABC", after a parent render "29ABC"
log: outer GstField mounted
same type, same place, other props: input still "abc"
Real run. The log lists the effects of GstField.
With the field defined inside, the parent's render replaced the input. What the user had typed was gone, and the log shows the inner component unmounting and mounting again. With the field defined at the top level, the same click left the text alone and the component mounted once. The last line shows the third rule: the same type in the same position with different props kept its state.
The fix is a habit more than a technique. Declare components at the top level of a module. If an inner piece needs the outer component's values, pass them as props.
The same rule explains a second surprise. React's guide on preserving state says that wrapping a component in a different parent element, for example changing a section to a div, resets everything beneath it, because the type at that position changed. A component that jumps between two wrappers on some condition loses its state each time. When a wrapper must change, keep the element type the same and change its props or class instead.
Resetting on purpose
Sometimes you want a fresh component, for example when the user opens a different invoice and the form must start empty. Changing the key does that, because a new key is a new identity at the same position.
tsx
function KeyedPanel({ id }: { id: string }) {
return <Note key={id} label={id} />
}
text
new key: input is ""
Real run. The key changed from INV-1 to INV-2.
The typed text disappeared with the key change, as intended. The state and effects chapter covered this as a way to remove effects that reset state. The same rule explains the index-key bug from the components chapter: with index keys the state stays with the position, not with the data.
Why this matters for speed
Identity bugs are performance bugs in disguise. A remount destroys DOM nodes, runs every effect cleanup and setup, and loses state. A subtree that remounts on every render costs far more than one that merely re-renders. When a component seems slow and also loses state, look for a nested definition before anything else.
Check your understanding
Why did the input lose its text when GstField was defined inside the form?
Each render of the form created a new function, which React treats as a new component type, so it removed the old field and mounted a new one.
What does changing the key of a component do?
It gives the component a new identity, so React unmounts the old one and mounts a new one, and its state starts again.
The same component type is rendered at the same position with different props. What happens to its state?
It is kept. In the run, Note still held "abc" after its props changed.
Part 3 · Fibers and the work loop
What a fiber is
React needs a data structure it can pause, resume and compare. It builds one object for each component instance and each DOM element in the tree, called a fiber. A fiber records what the node is, its props and state, and pointers to the fibers around it: its first child, its next sibling and its return, the parent that it returns to.
This is an implementation detail, and the code below uses private fields. They are not part of React's public API, they are not documented as stable, and a future version can rename or remove them. The lesson prints them to make the model concrete, not to give you something to build on.
Walking the tree
A parent with children does not hold an array of them. It holds one child pointer, and the children are linked with sibling. Walking the tree means following child down, sibling across and return back up.
The test mounts the ledger from earlier and prints its fiber tree.
text
root (tag 3, root)
Ledger (tag 0, function component)
button (tag 5, host element)
ul (tag 5, host element)
Row (tag 0, function component)
li (tag 5, host element)
Row (tag 0, function component)
li (tag 5, host element)
root fiber has an alternate after the first render: true
after one update, the root fiber is a different object: true
second.alternate === first: true
after two updates, third === first: true
return pointers from the last li: li > Row > ul > Ledger > root
Real run. Field names are internal and can change.
The tree has the shape of the components and the DOM elements together: a root, Ledger, its two host elements, and under the list a Row per invoice with its li. The numbers are React's internal tag for each kind of fiber. They match the cases in the installed react-dom-client.development.js file, where 3 is the root, 5 a host element, 6 text, 7 a fragment and 0 and 1 the function and class components. Like the field names, they are private and can be renumbered. The text inside the button is not a fiber of its own, because React handles a single text child directly.
The last lines show something more interesting. React keeps two copies of the tree. The one on screen is the current tree. When an update starts, React builds the next version in a second tree, the work-in-progress tree, reusing fibers through each fiber's alternate. Only at commit does the work-in-progress tree become current. In the run, the root fiber after one update was a different object from the one before, it pointed back to it through alternate, and after two updates the original was current again. The two trees swap.
Why a work loop
Because the work is stored as linked fibers and not as a deep chain of function calls, React can stop between two fibers and continue later. The loop that does this is the work loop. It processes one fiber, then asks whether it should keep going or give the browser a turn. Each update carries a priority, kept internally as a bit mask called lanes, so that an urgent update such as typing can be handled before low-priority work such as a transition.
You do not use lanes directly. You see their effect in two places. The concurrency chapter covered the user-facing tools, transitions and deferred values. The Scheduler track in the performance tools, which the next lesson uses, labels work as Blocking, Transition, Suspense or Idle, and those are the priorities in practice.
What to take from the model
Three consequences are worth keeping. Rendering a parent calls its children unless something stops it, because the work loop visits the child pointer. Rendering is separate from commit, so React can throw a half-finished work-in-progress tree away and start again without the user noticing. And a component that renders often is paying for each fiber it touches, which is why a smaller tree is the first cheap win.
Check your understanding
What are child, sibling and return on a fiber?
Pointers to the first child, the next sibling and the parent. They link the tree so React can walk it, pause and resume.
Why does React keep two trees?
It builds the next version as a work-in-progress tree without touching the one on screen, and swaps them at commit. In the run the two root fibers traded places after each update.
A library reads fiber.child and fiber.tag to find components and breaks after a React upgrade. Why?
Those fields are private internals, so a release can rename or renumber them. Code that depends on them has no guarantee. The lesson printed them only to explain the model; for your own code, use public APIs such as refs and context.
Part 4 · Measuring before fixing
Guessing is expensive
A slow screen has many possible causes: too many components rendering, one component doing heavy work, too many DOM nodes, or a layout problem the browser has to solve. Optimising the wrong one leaves the screen slow and the code harder to read. Measure first, find which step is slow, and then fix that step.
Two tools give you the numbers. The Profiler component reports how long a subtree took to render. React's performance tracks put React's own work on the Chrome performance timeline.
The Profiler component
<Profiler id onRender> wraps a part of the tree. Each time that part commits, React calls onRender with the id, the phase (mount, update or nested update), the actualDuration in milliseconds that rendering the subtree took for this update, and the baseDuration, an estimate of how long it would take to render the whole subtree again without any memoisation. The react.dev reference says comparing the two shows how well memoisation is working.
tsx
const rows: string[] = []
const onRender: ProfilerOnRenderCallback = (
id,
phase,
actual,
base,
) => {
const ms = (n: number) => n.toFixed(1) + ' ms'
rows.push(
`${id} ${phase.padEnd(6)} actual ${ms(actual)}, base ${ms(base)}`,
)
}
// <Profiler id="ledger" onRender={onRender}> wraps the tree
The ledger below has 300 rows wrapped in memo, which a later lesson in this chapter explains, and a note field above them. The test mounts it and then types two characters.
text
ledger mount actual 20.0 ms, base 8.5 ms
ledger update actual 4.5 ms, base 10.0 ms
ledger update actual 4.2 ms, base 9.8 ms
One run in jsdom, development build. The numbers vary from run to run.
In this run the mount cost more than the base estimate, because it created everything. Each update reported an actual duration well below its base duration, because the memoised rows were skipped and only the input rendered. A large gap between the two numbers is memoisation doing its job.
Profiling is switched off in the production build to avoid its overhead, according to the reference. To profile a production build you need React's special profiling build.
The performance tracks
In a development build, React adds its own tracks to the browser's Performance panel. The Scheduler tracks show work by priority, in four rows named Blocking, Transition, Suspense and Idle. The Components track shows how long each component took, as a flame graph. For a click, the Blocking track shows the phases: the event, the render, the commit and the effects that remain.
Chrome DevTools draws these from a trace, and a script can capture the same trace through the DevTools protocol. The lab app has a list of 500 rows, all rendered without memoisation, and a button that adds one.
development build, one click on "add" (501 rows after it)
Scheduler, Blocking track:
Event: click 3.1 ms
Render 14.4 ms
Commit 2.0 ms
Remaining Effects 1.5 ms
Components track entries: Ledger 1, Row 501
One run in headless Chrome, development build. Times vary from run to run.
React's own time for the click was about 18 ms in all: 14.4 ms of render, with a small commit and a small effect phase. Like every timing here, it comes from one run on this machine and varies. The Components track names the cause: one Ledger entry and 501 Row entries. The ledger rendered every row, though only one was new. That points at the next lesson, and it is the kind of fact a guess would have missed.
The tracks also mark trouble. React's reference describes a cascading update: an update scheduled during a render pass, which can make React discard work and start again. The development build shows it as its own entry, and clicking it shows the method that scheduled the update. If you see one in the Blocking track, look for a setState call in an effect or a layout effect that runs straight after a render. The reference adds that the Components track shows only effects that took 0.05 ms or longer or triggered an update, so a missing effect usually means a cheap one that changed nothing.
Check your understanding
What does a large gap between baseDuration and actualDuration show?
Memoisation is working. The subtree rendered much less than it would have without it.
Why does the Components track entry count matter in the run?
It showed 501 Row entries for one click, so the whole list rendered although one row was new.
Why was development used for these measurements?
The Profiler and React's performance tracks are off in the production build by default.
Part 5 · Cheap fixes first
Do less before memoising less
Many slow renders are fixed by moving things around, with no memoisation at all. These fixes work because they change which components render, not how fast each one is. They also make code simpler, so try them first.
Move state down
If only one small part of a component uses a piece of state, put the state in a component of its own. The search text below belongs to the input and to nothing else, yet it sits in the ledger, so every keystroke renders every row.
The test types one character into each version and counts the rows that render.
text
state kept at the top: one keystroke renders 200 rows
state moved into SearchBox: one keystroke renders 0 rows
rows built beside the counter: one click renders 200 rows
rows passed in as children: one click renders 0 rows
Real run. The ledger has 200 rows.
With the state at the top, one keystroke rendered 200 rows. With the state moved into SearchBox, it rendered none. Putting state near where it is used is also called colocation.
Pass the slow part in as children
Sometimes the state has to stay in a wrapper that also holds expensive content. The wrapper can take that content as children. The children element is created by the wrapper's parent, so when the wrapper's own state changes, the same element is handed back and React skips it.
The second pair of lines in the output shows the effect. With the rows built next to the counter, a click rendered 200 rows. With the rows passed in as children, a click rendered none.
Split big components
A component that does five things renders all five when any input changes. Splitting it into smaller components lets React reuse the parts that did not change. Together with colocation, this is often enough: the first two fixes need no new API and no dependency lists to maintain, so they cannot go stale.
Splitting also helps for a quieter reason: it limits the blast radius of a change. A header, a table and a footer in one component all render whenever the footer's clock ticks. As three components, only the footer does. The counters in this lesson are the same tool you would use to confirm a split worked: render a count, change the input, and read the number.
These fixes have a limit. Moving state down only works when the state is used by one subtree. If a filter drives both a toolbar and a table, the state has to live above both, and the table renders when the filter changes. That table render is legitimate, and the later fixes in this chapter apply to it, not to the state.
Each of these fixes can be checked with the same kind of counter used above: put a counter in the component body, make the change and read the number again. A fix that does not move the number was not the cause.
An order to work in
First, find the render that is too slow, with the Profiler or the trace.
Second, move state down to the component that uses it.
Third, pass expensive content in as children where state must stay up.
Fourth, split components so the parts that change are small.
Only then add memo, which the next lesson covers.
React's reference for useMemo gives the same order of preference. It says that moving state down and accepting JSX as children often remove the need for memoisation.
Check your understanding
Why did the rows not render when the search state moved into SearchBox?
The ledger no longer owned the state, so typing rendered only SearchBox. The rows' parent did not render.
Why does passing content as children skip it when the wrapper's state changes?
The children element is created by the wrapper's parent, which did not render, so React receives the same element and skips it.
Why try these fixes before memo?
They need no comparison logic and no dependency lists, so they cannot go stale, and they leave the code simpler.
Part 6 · memo, useMemo and useCallback
What each tool does
memo wraps a component so React skips rendering it when its props are equal to the last render's. The comparison is shallow: each prop is compared with Object.is. A new object, array or function on each render counts as changed. useMemo caches the result of a calculation between renders, and useCallback caches a function. All three depend on stable references, so they work as a set.
The react.dev reference lists what memo does not prevent. A memoised component still renders when its own state changes, and when a context it reads changes. It only skips renders that come from its parent.
The callback that defeats memo
The ledger below renders 100 rows. A variant prop selects four ways to pass props, so one test can compare them.
The test selects row 5, then row 7, and counts how many rows render for the second click. Row 5 loses the selection and row 7 gains it, so two rows have a changed selected prop.
text
no memo select row 7 after row 5: 100 renders
memo, inline callback select row 7 after row 5: 100 renders
memo, inline object select row 7 after row 5: 100 renders
memo, stable callback select row 7 after row 5: 2 renders
Real run. Each line is the second click.
Without memo, all 100 rows rendered. With memo but an inline callback, all 100 still rendered, because the callback is a new function each time. With memo but an inline object passed as a prop, again 100. Only with memo and a stable callback did the count drop to the 2 rows whose selected prop changed.
Watch for which memoised rows skip when the callback is a new function each time
Read it as steps
With an inline callback every row renders; with a stable one only two do
Memoisation is easy to pay for and not collect. Each memo adds a comparison on every parent render. If a prop changes every time, as in three of the four variants, the comparison fails and the component renders anyway, so you have added the cost with no saving.
useMemo for values
useMemo serves two purposes: avoiding an expensive calculation, and keeping a value's reference stable for a memoised child. The test below measures both.
filter in the body: one keystroke runs it 1 times
filter in useMemo: one keystroke runs it 0 times
memo Chart, inline object: one keystroke renders it 1 times
memo Chart, useMemo object: one keystroke renders it 0 times
Real run. One keystroke in an unrelated input.
Without useMemo, the filter over 5,000 invoices ran on every keystroke. With it, it did not run. The Chart below memo rendered on each keystroke when it got an inline { max: 900 } object, and did not when the object came from useMemo.
The reference calls useMemo a performance hint and not a guarantee: React may drop the cache, so the code must work without it. It also says to add it for measured slowness, not by habit.
useCallback(fn, deps) is the same cache for a function, and memo accepts a second argument, a custom comparison, if the default one does not fit. The reference warns that a custom comparison must compare every prop, including functions, or a changed handler is ignored and the component calls a stale closure. Deep comparisons are also slow on big objects. Most code should stay with the default shallow check and fix the props instead.
A short rule
Measure first. Fix with colocation and children before memoising. When you do memoise, keep the whole chain stable: memo on the child, useCallback for its functions, useMemo for its objects. And remember that the compiler in the next lesson can do most of this for you.
Check your understanding
Why did memo with an inline callback still render 100 rows?
The inline function is new on every parent render, so the prop comparison with Object.is fails for every row.
A memoised child reads a context. What happens when the context changes?
It renders again. memo only skips renders caused by the parent, not those from its own state or context.
When is useMemo worth adding?
When a calculation is measurably expensive, or when it keeps an object or array stable for a memoised child or another hook's dependency list.
Part 7 · The React Compiler
Memoisation, automated
Everything in the last lesson was manual: you decide what to wrap and you maintain the dependency arrays. React Compiler is a build-time tool that does it for you. It analyses each component and hook and inserts caching so that values and JSX are recomputed only when their inputs change. React's 1.0 announcement says it works with React 17 and up, and that it can memoise things manual memoisation cannot, such as code after an early return.
It relies on the Rules of React. A component must be pure, must not mutate props or state, and must follow the rules of hooks. Code that breaks them is skipped, and a lint rule tells you which. The lab confirmed the skipping: running the compiler on the two lint examples further down returned both files unchanged, with no cache.
What the output looks like
The compiler is a Babel plugin. The lab runs it on a small component and prints the result.
tsx
type Line = { amount: number }
exportfunction Summary({ lines, onPick }: {
lines: Line[]
onPick: (total: number) => void
}) {
const total = lines.reduce((sum, l) => sum + l.amount, 0)
return <button onClick={() => onPick(total)}>total {total}</button>
}
text
import { c as _c } from "react/compiler-runtime";
export function Summary(t0) {
const $ = _c(8);
const {
lines,
onPick
} = t0;
let t1;
if ($[0] !== lines) {
t1 = lines.reduce(_temp, 0);
$[0] = lines;
$[1] = t1;
} else {
t1 = $[1];
}
const total = t1;
Real output of babel-plugin-react-compiler 1.0.0, first part.
text
let t2;
if ($[2] !== onPick || $[3] !== total) {
t2 = () => onPick(total);
$[2] = onPick;
$[3] = total;
$[4] = t2;
} else {
t2 = $[4];
}
let t3;
if ($[5] !== t2 || $[6] !== total) {
t3 = <button onClick={t2}>total {total}</button>;
$[5] = t2;
$[6] = total;
$[7] = t3;
} else {
t3 = $[7];
}
return t3;
}
function _temp(sum, l) {
return sum + l.amount;
}
The rest of the compiled function.
The line const $ = _c(8) asks React for a cache with eight slots, from react/compiler-runtime. Each block then checks whether its inputs changed. The sum is recomputed only if lines is a different array. The click handler is rebuilt only if onPick or total changed, and the final element only if one of its pieces changed. The output is the same memoisation you would write by hand, derived from what each value reads.
What it fixes and what it does not
The test runs two components, as written and compiled, and counts calls.
text
Panel, source as written: one keystroke calls Total 1 times
Panel, compiled: one keystroke calls Total 0 times
Ledger, source as written: selecting a row calls Row 100 times
Ledger, compiled: selecting a row calls Row 100 times
Real run. "Panel" is a parent with a field and a `Total` child.
In the panel, the child was called once per keystroke as written, and not at all when compiled. The compiled Panel has this block for the child:
text
let t3;
if ($[3] !== lines || $[4] !== probe) {
t3 = <Total lines={lines} probe={probe} />;
$[3] = lines;
$[4] = probe;
$[5] = t3;
} else {
t3 = $[5];
}
From the compiled Panel. The element is rebuilt only when `lines` or `probe` changes.
The compiler cached the <Total /> element, so React received the same element and skipped the child. In the ledger, selecting a row still called Row 100 times in both versions. The compiled ledger shows why.
From the compiled Ledger. One long line is wrapped to fit.
The rows are created inside a callback that is part of one cached value, which is rebuilt when selected changes. The compiler gave each row element no cache of its own, and the inline onSelect stays inside the callback as a new function each time. So every Row is still called. The compiled Row caches its own output, so each call is cheap when its props are unchanged, but the call still happens, and the probe counter inside it runs every time. That is the honest limit of the compiler: it removes work inside a render, not the visit to every component. For long lists, windowing, in the last lesson, is the fix that counts.
Using it with Vite
With @vitejs/plugin-react 6 or later, the compiler runs through @rolldown/plugin-babel. React's installation guide lists two packages to install, babel-plugin-react-compiler and the Babel plugin, and the configuration below. The older inline babel option of the React plugin was removed in version 6.
plain: bundle 219.88 kB │ gzip: 68.75 kB
plain: memo_cache_sentinel appears 1 time(s) in the bundle
compiler: bundle 220.41 kB │ gzip: 69.04 kB
compiler: memo_cache_sentinel appears 2 time(s) in the bundle
Real output of `vite build` in both modes.
The compiled bundle is a little larger, and the cache check appears one more time in it, for the one component in the lab app. The compiler pays for itself on screens with real rendering work, not on a tiny demo.
Lint rules and opting out
The compiler's analysis is available as lint rules in eslint-plugin-react-hooks, so you can find code the compiler would skip without installing it. Two examples below.
bad.jsx:5:14 react-hooks/refs
Error: Cannot access refs during render
bad2.jsx:5:3 react-hooks/set-state-in-render
Error: Cannot call setState during render
Real run of ESLint 10 with the plugin's recommended-latest configuration.
If a compiled component misbehaves, a "use no memo" directive at the top of its body opts it out. The lab output confirms it: the component compiled to itself, with no cache.
text
export function Skipped({
n
}) {
'use no memo';
return <p>{n * 2}</p>;
}
Real output for a component with the directive.
Exact pinning is sensible: the announcement says memoisation behaviour may change in later versions and suggests pinning if tests are thin. Existing useMemo and useCallback calls stay valid, and the announcement advises leaving them in place.
Check your understanding
What does _c(8) do in compiled output?
It allocates a cache of eight slots for this component. Each slot holds an input or a result, and the generated code recomputes a value only when its inputs differ.
In the run, why was Total skipped after compiling but Row not?
<Total /> sits at a fixed place and its element was cached. The rows are created inside a map callback with no cache of their own, so each was still called.
What does "use no memo" do?
It tells the compiler to leave that component alone. The compiled output was the source, with no _c cache.
Part 8 · Long lists: windowing
Why a list can be slow however you render it
After memoisation, one more cost remains: the number of DOM nodes. A browser must lay out and paint every node, even if the user sees fifteen of them. A ledger with ten thousand rows creates tens of thousands of elements.
Windowing, also called virtualisation, renders only the rows in or near the viewport, and keeps a tall empty box so the scrollbar still means the whole list. As the user scrolls, the set of rendered rows changes.
By hand
The idea is arithmetic. With a fixed row height, the first visible row is the scroll offset divided by the row height. Render that row and a screenful after it, plus a few extra rows above and below, called overscan, so fast scrolling does not show gaps. Position each row absolutely at its own offset inside a box of full height.
The component keeps the scroll offset in state and slices the array. Row height is a constant, which is why this version only works for equal-height rows.
With a library
TanStack Virtual does the same arithmetic, plus measuring rows of unknown height and keeping scrolling stable. The React adapter's hook returns the visible items and the total size.
The lab builds the three variants for production and loads each into headless Chrome five times. The page renders with flushSync, forces a layout and records the time, then selects a row the same way. The script prints the median of the five loads, and the whole script was run five times to see how steady the medians are.
production build, 10,000 invoices, median of 5 page loads
mode li rows elements mount ms select ms
plain 1000040008303.139.0
hand 2410415.21.6
virtual 188017.60.8
The last of five runs of the script, headless Chrome, production build. Timings vary.
The plain list put 10,000 rows and about 40,000 elements in the DOM, and its mount took a few hundred milliseconds on this machine, with all the rows rendering again to select just one. The hand-windowed list rendered 24 rows and the library list 18. Both mounted in tens of milliseconds, and a selection took about a millisecond.
text
same five loads, fastest to slowest (ms)
mode mount select
plain 248.9 to 341.633.6 to 42.3
hand 14.5 to 18.01.2 to 1.7
virtual 15.9 to 20.80.8 to 1.1
The five loads behind that run, fastest to slowest.
The spread is large for the plain list, so read the numbers as a range. Across five runs of the script, the median mount of the plain list was between 232 and 365 ms, and its single loads ran from 215 to 406 ms.
Run
Plain mount
Hand mount
Virtual mount
Plain select
1
231.9
13.5
14.4
31.9
2
365.0
13.0
18.0
43.8
3
336.0
14.5
18.6
42.4
4
289.2
13.8
19.2
34.4
5
303.1
15.2
17.6
39.0
1
Plain mount231.9
Hand mount13.5
Virtual mount14.4
Plain select31.9
2
Plain mount365.0
Hand mount13.0
Virtual mount18.0
Plain select43.8
3
Plain mount336.0
Hand mount14.5
Virtual mount18.6
Plain select42.4
4
Plain mount289.2
Hand mount13.8
Virtual mount19.2
Plain select34.4
5
Plain mount303.1
Hand mount15.2
Virtual mount17.6
Plain select39.0
The plain list's median moved by more than half from run to run, while the windowed lists stayed between 13 and 19 ms. The ratio of plain to hand-windowed mount ran from about 17 to about 28 across the five runs, so the conclusion does not depend on which run you read: windowing cut the mount by more than an order of magnitude.
Animated sceneTen thousand invoices, rendered three ways0:16
Hand windowing against plain, mount: about 20x less (303 / 15.2 in this run; 17x to 28x across five runs)
Read it as steps
Numbers from the last of five runs of the production build on this machine; the plain list varied by about 1.5x between runs
The numbers 14 and 10 in the hand-written version come from the geometry. A 400 px box shows about 13 rows of 32 px, so the code renders 14 plus ten more for overscan, five above and five below. Change the box height or the row height and those numbers change with them, which is another thing a library tracks for you. The library also measures rows whose height is not known in advance and keeps scrolling stable while it learns the real sizes. The hand-written version cannot, so it is only suited to rows of one fixed height.
When to window
Windowing is a trade. Browser find-in-page cannot see rows that are not in the DOM, keyboard focus can leave the window of rendered rows, and anchored scrolling needs care. For lists of a few hundred rows, the earlier fixes are enough. Past a few thousand rows, or when each row is expensive, windowing is the fix that scales.
Scroll position needs a plan too. When the user opens an invoice and comes back, a windowed list starts at the top unless you save the offset and restore it. Libraries expose a way to scroll to an index or an offset, and the hand-written version can set scrollTop in an effect. Plan for this before choosing windowing, because a list people leave and return to is common in a ledger.
Check your understanding
What does the invisible tall box in a windowed list do?
It gives the scroll container the full height of the list, so the scrollbar and scroll positions behave as if every row existed.
Why was selecting a row so much slower in the plain list?
Every one of the 10,000 rows rendered again, and the windowed lists rendered only the 18 or 24 near the viewport.
Name one thing windowing costs you.
Rows outside the window are not in the DOM, so find-in-page cannot see them and focus can leave the rendered rows.