How to profile React app performance with the Profiler API

· Category: React

Short answer

The React Profiler measures how often a component renders and the time each render takes. It helps identify performance bottlenecks in your component tree.

Steps

  1. Import Profiler from react.
  2. Wrap a section of your app in <Profiler id="Name" onRender={callback}>.
  3. In the callback, log actualDuration, baseDuration, and phase.

Example

import { Profiler } from 'react';

function onRender(id, phase, actualDuration) {
  console.log(id, phase, actualDuration);
}

function App() {
  return (
    <Profiler id="App" onRender={onRender}>
      <Dashboard />
    </Profiler>
  );
}

Tips

  • Use the Profiler in production builds sparingly; it adds overhead.
  • Combine with React.memo and useMemo to address slow renders identified by profiling.
  • React DevTools provides a visual profiler that is easier to use for most cases.