Sub topic 15
Verifying improvements and guarding against regressions
This chapter assumes you can record a session in the React DevTools Profiler and read its flamegraph and ranked charts. It also assumes you know the fixes from earlier chapters: state colocation, memo, useMemo, useCallback, useDeferredValue, and code splitting. Here you will confirm that a fix helped, and set up checks so the slowdown does not return.
Why a fix is only a hypothesis until you measure it
Every optimization is a guess about where time goes. The profiler can show that the guess was wrong. Memoization is the usual example. It adds comparison work on every render, and it does nothing if a prop changes identity each time. A change can leave the code more complex and the app no faster.
Verification means answering three questions with numbers:
- Did the target interaction get faster, by more than the noise between runs?
- Did the reason for the speedup match your theory? For example, did the component stop rendering, or did it only render faster?
- Did anything else get slower, such as the initial load or another screen?
Build a repeatable measurement
Timings from two different setups cannot be compared. Fix everything except the code change.
- Use the same build type. Compare production builds, or profiling builds, against each other. Development builds include extra checks, and StrictMode renders components twice, so their timings are inflated and uneven. Never compare a development "before" with a production "after".
- Script the interaction. Write it down as steps, such as "open the Orders page, type
abcinto the search box, wait for the list to settle". Do not rely on memory. - Use the same data. A list of 50 items hides problems that a list of 5,000 shows. Seed the app with the same dataset each time.
- Start from the same state. Reload the page before each run. Use a cleared cache, or keep it warm every time.
- Close other work. Browser extensions and background tabs add noise. Throttle the CPU (for example 4x slowdown in the browser's Performance panel) so differences stand out on a fast machine.
Record at least five runs per version. Use the median, not the best run, and look at the spread.
Choose metrics that survive noise
Raw milliseconds move around from run to run. Counts do not. Record both kinds.
| Metric | Where to read it | Noise | Use it to show |
|---|---|---|---|
| Commit count for the interaction | Profiler commit bar chart | Very low | Fewer updates reached the screen |
| Components rendered per commit | Flamegraph (gray means not rendered) | Very low | Memoization or colocation worked |
| `actualDuration` of the slowest commit | Profiler or `onRender` | Medium | The cost of one update dropped |
| Long tasks (over 50 ms) | Browser Performance panel | Medium | The page stays responsive |
| Gzipped bundle size | Build output | None | Load cost dropped |
If the commit count and the rendered-components count did not change, but the duration did, treat the result with suspicion. It may be noise.
Check that the mechanism changed
A good result has a visible cause. After applying a fix, record the same interaction and look at the flamegraph.
- After moving state down, the expensive sibling should appear gray in each typing commit. Open the "Why did this render?" information to confirm it no longer lists "parent rendered".
- After adding
memo, the memoized rows should be gray when only unrelated state changes. If they are still colored, a prop is changing identity. Check inline objects, inline arrow functions, and arrays rebuilt in the parent. - After
useDeferredValue, you should see two commits per keystroke. The first is cheap and updates the input. The second is the expensive one, and React can abandon it if you keep typing.
If the numbers improved but the mechanism did not change, find out why before you ship. The improvement may come from a different cause, or from a different data size.
Apply one change per loop. If you apply three fixes at once, you cannot tell which one helped, and you cannot remove the ones that did nothing.
Check for side effects
Optimizations move cost around. After a fix, re-measure these places:
- Mount time.
useMemoandmemoadd work to the first render. A screen that mounts slower may be a bad trade even if updates are faster. - Memory. Caches and virtualized lists keep data alive. Check memory in the browser's Memory panel if you cache large results.
- Other screens. A shared component you memoized, or a context you split, can change behavior elsewhere.
- Correctness. A stale
useCallbackoruseMemodependency list gives wrong output, not slow output. Run your normal tests and use the app by hand.
Guard against regressions with tests
Timing assertions in tests fail at random, because CI machines vary. Count renders instead. A render count is exact, and it catches the common regression: someone moves state back up, or adds an inline object that breaks memo.
The test below checks that typing in the search box does not re-render the expensive tree. It uses Vitest and React Testing Library. Render without StrictMode in these tests, or the counts double.
import { Profiler, useState } from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import { expect, test, vi } from "vitest";
const treeRenders = vi.fn();
function ExpensiveTree() {
treeRenders();
return <div>tree</div>;
}
function SearchBox() {
const [query, setQuery] = useState("");
return (
<input
aria-label="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
);
}
function Page() {
return (
<>
<SearchBox />
<ExpensiveTree />
</>
);
}
test("typing does not re-render ExpensiveTree", () => {
const onRender = vi.fn();
render(
<Profiler id="Page" onRender={onRender}>
<Page />
</Profiler>
);
// Ignore the mount.
treeRenders.mockClear();
onRender.mockClear();
fireEvent.change(screen.getByLabelText("search"), {
target: { value: "abc" },
});
expect(treeRenders).not.toHaveBeenCalled();
// One commit for the one input change.
expect(onRender).toHaveBeenCalledTimes(1);
});The test checks two things. ExpensiveTree must not render. The Profiler must report exactly one commit, which catches a change that makes one keystroke trigger a chain of updates.
If you later move query into Page, the first assertion fails. The failure names the interaction that regressed.
Guard the bundle size
Code splitting only helps while the split stays in place. One static import of the chart library into the main file puts it back in the main bundle. A size budget in CI catches this. The script below fails the build when the gzipped JavaScript in dist/assets is over budget. Save it as check-bundle.mjs.
import { readdirSync, readFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
import { join } from "node:path";
const dir = "dist/assets";
const budgetBytes = 170 * 1024; // gzipped, all entry-time JS
const files = readdirSync(dir).filter((f) => f.endsWith(".js"));
let total = 0;
for (const file of files) {
const size = gzipSync(readFileSync(join(dir, file))).length;
total += size;
console.log(`${file}: ${(size / 1024).toFixed(1)} KB gzipped`);
}
console.log(`Total: ${(total / 1024).toFixed(1)} KB (budget ${budgetBytes / 1024} KB)`);
if (total > budgetBytes) {
console.error("Bundle budget exceeded");
process.exit(1);
}This script sums every JavaScript file, including lazy chunks that load later. To budget only what loads at startup, list the entry file and its direct imports instead. Set the budget slightly above the current size, so small growth is visible and large growth fails the build.
Keep a record
Write the result in the pull request that contains the fix. Include the interaction, the build type, the data size, and the before and after values. For example:
| Metric | Before (median of 5) | After (median of 5) |
|---|---|---|
| Components rendered per keystroke | 412 | 3 |
| Slowest commit `actualDuration` | 68 ms | 4 ms |
| Long tasks during typing | 9 | 0 |
A reviewer can then check the claim, and a future developer can see what "good" looked like. This also helps when the numbers get worse later, because you know which commit to compare against.
Common mistakes
- Declaring victory from one run. The first run after a reload is often slow because of cold caches. Repeat runs and use the median.
- Comparing different builds. A development "before" and a production "after" shows a speedup that has nothing to do with your change.
- Asserting timings in unit tests. They fail randomly. Assert render counts, and keep timing checks for manual profiling or a dedicated performance job.
- Leaving
Profilercallbacks in production. The component is disabled in standard production builds. It works only in profiling builds, so do not expectonRenderdata from a normal release. - Keeping fixes that did nothing. If a
useMemoormemoshows no measured gain, remove it. It adds code and comparison cost.
Exercise
You wrapped a list row in memo and measured the typing interaction. The median slowest commit went from 40 ms to 38 ms, and the flamegraph still shows every row colored in each commit. What do you conclude, and what do you check next?
Show answer
The fix did not work, and the 2 ms difference is within noise. Rows still render, so memoization is being defeated by a prop that changes identity on each render, such as an inline arrow function, an inline object, or an array built in the parent. Check the "Why did this render?" information for the rows, find the unstable prop, stabilize it with useCallback or useMemo (or move it outside the component), and record again. Then confirm the rows are gray and the commit count and duration drop. If they stay colored, revert the memo change.
Exercise
Why is a render-count assertion a better regression test than a test that fails when a render takes more than 10 ms?
Show answer
A render count is deterministic. The same interaction gives the same count on every machine, so the test fails only when the code changes. A time limit depends on CPU speed and load, so it passes or fails at random on CI. A count also points at the cause, such as a component that should not have rendered.