Blog>
Snippets

React DevTools: Profiling and Debugging

Use the updated React DevTools to profile component rendering and optimize performance bottlenecks in a React app.
import React, { Profiler } from 'react';

function onRenderCallback(
  id, // the 'id' prop of the Profiler tree that has just committed
  phase, // either 'mount' (if the tree just mounted) or 'update' (if it re-rendered)
  actualDuration, // time spent rendering the committed update
  baseDuration, // estimated time to render the entire subtree without memoization
  startTime, // when React began rendering this update
  commitTime, // when React committed this update
  interactions // the Set of interactions belonging to this update
) {
  // Aggregate or log render timings...
  console.log(`Rendered ${id} with phase ${phase} taking ${actualDuration}ms`);
}

function MyComponent() {
  return (
    <Profiler id="MyComponent" onRender={onRenderCallback}>
      {/* ... */}
    </Profiler>
  );
}

export default MyComponent;
This code snippet shows how to use the Profiler API in your React components to log performance-related information. It includes an onRender callback that logs the rendering information, such as the component's identifier, phase of the rendering cycle, and the actual time taken to render.
<!DOCTYPE html>
<html>
<head>
  <title>React Profiling Example</title>
</head>
<style>
  .my-component {
    /* Your CSS styles here */
  }
</style>
<body>
  <div id="root"></div>
  <script src="path/to/react.js"></script>
  <script src="path/to/react-dom.js"></script>
  <script src="path/to/your-react-component.js"></script>
  <script>
    ReactDOM.render(
      <MyComponent />, 
      document.getElementById('root')
    );
  </script>
</body>
</html>
This HTML document sets up a webpage to render a React component with the Profiler API enabled. The Profiler is part of your React component (as shown in the previous JavaScript snippet), and this document includes the minimal HTML and script tags to render the component into the page.