Sub topic 12
Measuring in code with the Profiler component
This chapter assumes you can build React function components with props, state, and hooks. It also assumes you have recorded at least one session in the React DevTools Profiler. The DevTools Profiler is good for exploring. The Profiler component is good for measuring the same parts of your app repeatedly, in code, and sending the numbers somewhere.
What the Profiler component is for
Profiler is a component exported from react. You wrap a part of your tree in it, give it an id and an onRender callback, and React calls that callback every time something inside the wrapped tree commits an update.
Use it when you want to:
- Log render timings for one section of the app during development.
- Compare two implementations of the same component with the same interaction.
- Collect timings from real sessions and send them to an analytics service.
- Add an automated check that a screen does not get slower.
import { Profiler } from "react";
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// phase is "mount", "update", or "nested-update"
console.log(`${id} ${phase}: ${actualDuration.toFixed(1)}ms (base ${baseDuration.toFixed(1)}ms)`);
}
export default function App() {
return (
<Profiler id="Dashboard" onRender={onRender}>
<Dashboard />
</Profiler>
);
}Dashboard is a placeholder for your own component. Each time anything inside the Profiler commits, the console prints one line.
The onRender arguments
onRender receives six arguments, always in this order.
| Argument | Meaning |
|---|---|
| `id` | The `id` prop of the `Profiler` that reported. Use it to tell several profilers apart. |
| `phase` | `"mount"` for the first commit, `"update"` for later commits, `"nested-update"` for an update caused by a layout effect or similar work inside the commit. |
| `actualDuration` | Milliseconds spent rendering the wrapped tree for this update. |
| `baseDuration` | Estimated milliseconds to render the whole wrapped tree again with no memoization. |
| `startTime` | When React began rendering this update. |
| `commitTime` | When React committed this update. |
Timestamps are in the same clock as performance.now(), so you can line them up with marks you make yourself.
Reading actualDuration and baseDuration together
actualDuration tells you what this update cost. baseDuration tells you what a full re-render would cost. Compare them.
- If
actualDurationis much smaller thanbaseDuration, memoization or bailouts are skipping work. That is the intended outcome of the techniques in earlier chapters. - If the two are close on an update, almost everything under the
Profilerre-rendered. - On
"mount", the two are usually close, because nothing can be skipped on the first render. - A high
baseDurationwith a lowactualDurationstill means the worst case is expensive. A change that invalidates all memoization, such as a new context value, will cost close tobaseDuration.
What the callback does not tell you
The numbers describe render work only. They do not include browser layout, paint, or the time your own event handler took before React started rendering. For those, use the browser Performance panel, covered in a later chapter. The callback also does not name which component inside the tree was slow. To find that, put smaller Profiler wrappers around suspected parts, or use the DevTools flamegraph.
Where the Profiler component runs
Two facts decide whether you can trust what it reports.
- In a development build,
Profilerworks, and timings include extra development checks. They are inflated and useful only for comparing one change against another. - In a standard production build,
Profileris disabled. YouronRenderis never called, and the component adds almost nothing to your bundle. To profile production-like behaviour you need a special profiling build. How you enable it depends on your bundler. In a webpack setup, aliasingreact-domtoreact-dom/profiling(together withscheduler/tracing-profilingon older versions) enables it. Check your framework's documentation, because some frameworks provide a flag for this.
Profiling builds are slightly slower than normal production builds, because React keeps the bookkeeping that produces durations. Enable them deliberately, for a test environment or a small share of traffic.
A realistic setup: a reusable wrapper
Scattering console.log callbacks across files gets messy. A small wrapper keeps one place that decides what to do with timings.
import { Profiler } from "react";
const SLOW_MS = 16;
function report(id, phase, actualDuration, baseDuration) {
if (actualDuration < SLOW_MS) return;
console.warn(
`[slow render] ${id} (${phase}): ${actualDuration.toFixed(1)}ms actual, ${baseDuration.toFixed(1)}ms base`
);
}
export function Measured({ id, children }) {
return (
<Profiler id={id} onRender={report}>
{children}
</Profiler>
);
}Use it like this:
import { Measured } from "./Measured";
export function Page({ rows }) {
return (
<main>
<Measured id="Toolbar">
<Toolbar />
</Measured>
<Measured id="Table">
<Table rows={rows} />
</Measured>
</main>
);
}Toolbar and Table are placeholders for your own components. Separate ids let you see which section produced a slow commit. The 16 ms threshold is roughly one frame at 60 frames per second. Treat it as a starting point, because your render shares that frame with layout and paint.
Nesting and what counts
Profilers can be nested. An outer Profiler reports on every commit that touches anything inside it, including the inner one. An inner Profiler reports only for commits that touch its own subtree.
A few rules follow from this:
- The
actualDurationof an outer profiler includes its children's time. - If a sibling outside an inner profiler updates, the inner profiler does not report.
- If a parent re-renders and a memoized child inside the profiler is skipped, the child's profiler may not report at all. Silence from a profiler can be good news.
Each Profiler adds a little overhead, so use it where you need an answer. Do not wrap every component.
Sending measurements to a service
Because onRender runs on each commit, sending a network request from it for every update is wasteful. Collect samples and send them in batches.
const samples = [];
function collect(id, phase, actualDuration, baseDuration, startTime, commitTime) {
samples.push({ id, phase, actualDuration, baseDuration, commitTime });
}
function flush() {
if (samples.length === 0) return;
const body = JSON.stringify(samples.splice(0, samples.length));
navigator.sendBeacon("/metrics/render", body);
}
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") flush();
});
export { collect };Pass collect as the onRender prop of a Profiler. sendBeacon queues a small POST that the browser delivers even while the page is being closed. Flushing on visibilitychange is the dependable moment to send, because unload events are unreliable on mobile browsers.
Keep the callback cheap. onRender runs during the commit, so slow work inside it makes the very thing you measure slower. Push a small object and return.
Comparing before and after
The Profiler component is most useful for a controlled comparison.
- Wrap the area in a
Profilerwith a stableid. - Perform the same interaction several times, such as typing ten characters or opening a panel.
- Record
actualDurationfor each commit. Take the median, not a single run, because the first run includes warm-up costs and any run can be disturbed by garbage collection. - Make one change.
- Repeat the same interaction and compare medians.
function median(values) {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
const updates = [];
export function recordUpdate(id, phase, actualDuration) {
if (phase === "update") updates.push(actualDuration);
}
export function summary() {
return { count: updates.length, medianMs: median(updates) };
}Call summary() from the browser console after the interaction. Ignoring "mount" commits keeps the comparison about updates only. Always compare the same kind of build on the same machine. A development number against a profiling number says nothing.
Common errors
- Passing an inline function that changes every render. An
onRenderdefined inside a component is a new function on each render. It works, but it is wasted work. Define it at module level, as above. - Forgetting
id.Profilerrequires it. Without it you cannot tell reports apart. - Reading numbers from a production build and getting nothing. The callback is disabled there, as explained earlier.
- Trusting a single sample. One slow commit is often the first run or a garbage collection pause.
- Treating
actualDurationas total time to screen. It excludes your handler, layout, and paint. - Doing heavy work inside
onRender. It skews the result and slows the user.
How this fits with the other tools
Exercise
A Profiler wraps a memoized list. After you type in a sibling input, onRender reports actualDuration 1.2 ms and baseDuration 48 ms. What do the two numbers tell you, and why might your production analytics receive no reports at all?
Show answer
The small actualDuration against the large baseDuration shows that memoization skipped almost all of the list, so this update was cheap. The list would cost about 48 ms if everything re-rendered. Analytics may be empty because Profiler callbacks do not fire in a standard production build. You need a profiling build to get reports from the deployed app.
Exercise
Write an onRender handler that ignores mounts and logs a warning only when an update takes more than 16 ms.
Show answer
function onRender(id, phase, actualDuration) { if (phase !== "mount" && actualDuration > 16) { console.warn(${id} took ${actualDuration.toFixed(1)}ms); } }