Capítulo 68 de 116

Chapter 68: Profiler

Core Idea

<Profiler> measures the actual rendering cost of a subtree programmatically — wrap any part of the tree in it, supply an onRender callback, and get timing data on every commit for that subtree, useful for automated performance regression tracking outside the DevTools Profiler UI.

Key Concepts

  • Props: id (a string identifying this Profiler in the callback data) and onRender (a callback function React calls after every commit within the wrapped subtree).
  • onRender receives detailed timing data: which Profiler id, the phase ("mount" for the first render, "update" for subsequent ones), actualDuration (time spent rendering this commit), baseDuration (an estimate of how long the subtree would take without any memoization), plus commit start/end timestamps.
  • Nesting Profilers: multiple <Profiler> components can be nested to measure different granularities within the same tree — each fires its own onRender independently.
  • Adds runtime overhead: measuring has a real cost — the docs frame this as a tool to add deliberately (often removed or gated in production), not something to wrap the whole app in by default.
  • Complements, doesn't replace, the DevTools Profiler: the browser extension's Profiler panel (Ch 10) is for interactive, human-driven investigation; the <Profiler> component is for programmatic, automated measurement (e.g. feeding into performance monitoring/CI).

Code Examples

<Profiler id="Sidebar" onRender={(id, phase, actualDuration) => {
  logPerf({ id, phase, actualDuration });
}}>
  <Sidebar />
</Profiler>
  • What it demonstrates: wrapping a subtree to record its render cost on every commit, feeding the data into a custom logging function instead of (or alongside) manual DevTools inspection.

Key Takeaways

  1. Use <Profiler> for programmatic/automated performance measurement; use the DevTools Profiler panel (Ch 10) for interactive investigation.
  2. It adds real runtime overhead — scope it to specific subtrees you're actively measuring, not the whole app by default.
  3. actualDuration vs. baseDuration is the key comparison for judging whether existing memoization is actually paying off.

Connects To

  • Ch 10 (React Developer Tools): the interactive counterpart to this programmatic measurement tool.
  • Ch 22 (Render and Commit): the commit event this component's onRender callback fires in response to.