Table of contents
1.
Introduction 
1.1.
Prerequisites required:
1.2.
Tools Used to Measure the Performance:
2.
React Profiler API
2.1.
Usage of React Profiler API
2.2.
The 'onRender' callback
3.
What is memoization?
4.
What is memoization in React?
5.
React Application's Performance Profiling 
6.
What is React Devtools Extension?
7.
Why is Profiler Component required?
8.
Profiler in React applications
9.
Frequently Asked Questions
10.
Key Takeaways
Last Updated: Mar 27, 2024

React Profiler

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Suppose you've just finished developing a new React app and want to learn more about its performance before releasing it to your clients. While the User Timing API(Application Programming Interface)  in the browser can be used to measure the rendering times of your components, the React team has introduced a better alternative: the React Profiler API and a Profiler tab in React DevTools.

Since it is entirely compatible with features like time-slicing and Suspense, the React Profiler API is the recommended approach to measure the rendering times of our components.

Prerequisites required:

  • React version 16.5 or higher is required for the application.
  • Your browser must have the React DevTools Extension installed.

Knowledge of React performance optimization and component level memoization with React.memo is also advantageous.

Tools Used to Measure the Performance:

In React, there are numerous techniques for measuring performance optimization. However, the React profiler DevTool and the React Profiler API are the focus of this article.

It's crucial to remember that performance is a compromise before moving on. As a result, after optimization, your application may become slower.

To measure the success or failure of the applied strategies, you should utilize tools like the React Profiler DevTool and the React Profiler API.

React Profiler API

The profiler analyzes how frequently a React application renders and how much it costs to render. Its goal is to discover slow areas of an application that could benefit from optimizations like memoization.

To help discover slow bottlenecks in apps, the React Profiler API analyses renders and the cost of rendering.

Note: Since profiling adds additional overhead, it is deactivated in the production build.

React provides a separate production build with profiling enabled if you want to use it in production.

Usage of React Profiler API

A Profiler can be placed anywhere in a React tree to determine how much it costs to render that section. It takes two parameters: an id (string) and an onRender callback (function), which React invokes whenever a component in the tree "commits" an update.

Let us take an example to profile a Navigation component and its descendants:

render(
  <App>
  // Multiple profiler components
  <Profiler id="Panel" onRender={callback}>
    <Panel {...props}>

      <Profiler id="Content" onRender={callback}>
        <Content {...props} />
        </Profiler>

      <Profiler id="PreviewPane" onRender={callback}>
        <PreviewPane {...props} />
        </Profiler>
      </Panel>
    </Profiler>
  </App>
);
You can also try this code with Online Javascript Compiler
Run Code
Note: Although Profiler is a lightweight component, it should only be used when absolutely necessary; each use adds to an application's CPU and memory overhead.

The 'onRender' callback

Every time the root renders, the onRender callback is invoked. The following parameters are passed to it:-

  • id: 'string'

The 'id' value of the profiler tag was measured. (If this id is obtained from state or props, it may change between renders). If you're using multiple profilers, this can help you determine which portion of the tree was committed.

  • phase: 'string'

"Mount" or "update" are the two options available (depending on whether this root was newly mounted or has just been updated).

  • actualTime: 'number'

For the most recent "mount" or "update" render, the time spent on rendering the Profiler and its descendants is the actualTime.

  • baseTime: 'number'

Within the profiler tree, the duration of the most recent render time taken for each individual component is the baseTime.

  • startTime: 'number'

When the profiler started the render that had just been committed is the startTime.

  • commitTime: 'number'

The time of the most recent commit is the commitTime.

  • interactions: ‘Set’

When the update was scheduled, a set of "interactions" was being tracked (e.g., when render or setState were called).

What is memoization?

Throughout its lifespan, an application executes multiple expensive, long-running computations. Memoization is the concept of handling these computations in a pure function. All of the computation's dependencies are supplied as arguments, and the function's value is cached when it returns. The cached value is returned whenever the function is called with the same arguments. As a result, there are no needless function calls, and time-consuming long-running I/O(Input/Output) can happen in an instant. This has a significant performance boost.

What is memoization in React?

Memoization can be used in a variety of ways in a React application. For this, React provides the useMemo and useCallback Hooks. Memoization is used behind the scenes in libraries like Reselect, and utility libraries like lodash provide a _.memoize function.

The React functional component is taken as an argument in the React.memo method. It remembers its current rendered output and avoids unnecessary re-renders, thus the component will only be re-rendered if its props change.

The purpose of performance optimization is to measure each component's load time, identify the components that are creating performance issues, and correct them.

React Application's Performance Profiling 

A key tool in any front-end developer's toolkit is knowing how to profile a React application to boost real-world speed. We can accomplish just that with the Profiler API, which gives us insights into why and how long our components are rendering.

We may utilise the profile data to identify unneeded and costly renderings that are negatively harming performance. Fortunately, it's not that difficult. Let's look at the Profiler API, which is included with every React installation.

There are two ways to use the React Profiler API:

  • React Devtools extension
  • Profiler Component 

Both give you the ability to engage with the same data in various ways. It is up to you to decide which one is best for you. We'll go over how to utilise the Profiler API to measure and enhance the performance of a React project by the end of this blog.

What is React Devtools Extension?

The Devtools profiler makes profiling a React application straightforward and visual. We can observe components that re-render visibly, and we can even trace the source of the render. We can make decisions based on this information to avoid wasteful renderings and improve performance.

Component chart shows all of the components in a commit that are being profiled. To grasp the concept of a commit, we must first grasp how React produces a component. It accomplishes this in two stages - 

  1. Render Phase

It determines what changes should be made, for example, DOM(Document Object Model) during the render phase. React calls the render and then compares the result to the previous render during this phase.

2. Commit Phase

React implements any modifications or changes during the commit process. (This is when React DOM inserts, changes, and removes DOM nodes in the case of React DOM).

A commit is essentially all of the changes made during the render phase. A render may or may not result in a commit (i.e., no new modifications), but a commit is always the result of a render, thus you may think of a commit as a render even if they don't mean the same thing.

For performance data, React Profiler offers four different chart views.

  1. Interaction Chart 

This is an experimental API that can help you figure out what caused an update in your app.

If you browse to a specific location in your application, like in an instance, this will be tracked as an interaction and presented in the Profiler tab. For each interaction, the commits connected to this interaction will also be displayed. This has been recently added to React.

2. Component Chart 

When you double-click a component, the component chart displays. During the profiling process, this view will offer information on the component lifespan. The data is shown in the form of a bar chart, with each bar indicating when the component was rendered and the length of the bar indicating how long it took to render.

3. Flame Chart 

This chart depicts the state of your application at the time of a single commit. Each bar represents a component, and the length of the bar indicates how long the component takes to render.

4. Ranked Chart

The Ranked chart view is available when you click the "Ranked" button in the Profiler tab. This view displays the component order based on the amount of time it took to render them. The components that took the most time will be at the top of the list. At a glance, this view shows which components are bottlenecks and have the most impact on page reloads.

Why is Profiler Component required?

This is a more basic way of working with the same profile data as the extension. The Profiler component provides a more textual manner of profiling a React project, rather than a visual representation of performance using colours and bar lengths.

It is, in fact, what the extension utilises behind the scenes to visualise the performance data. This makes it more adaptable to utilise because you can do whatever you want with the data. You could, for example, display it as a graph or store it in a database to track performance improvements over the course of your app's existence.

Profiler in React applications

Simply navigate to the profiler tab and press the Record button to get started to profile our application. After that, we'll execute actions in our app before pressing the record button to end profiling. Using a fancy flame chart, the DevTools will show us all of the updates while recording.

This is the React DevTools profiler, and you can now "Start profiling" the application by clicking the small blue circle.

To "Stop profiling", click the small red circle.

React compares the generated component tree with the current one every time one of our components renders. If any modifications are made, React will apply them to the DOM in a phase called commit. If we click on one of those commits, the flame chart below will be updated, with horizontal bars representing the components that changed in that commit. The longer the bar, the longer it took to render that component.

The profiler tab in React DevTools is a good method to analyse how our app is functioning without changing our code. We'll be able to see where rendering time is going and find bottlenecks that make our app sluggish simply by capturing important interactions.

Check out this problem - Count Ways To Reach The Nth Stair 

Frequently Asked Questions

 

  1. What are the problems with React Profiler?

Ans: Two problems with React Profiler are:

  • Multiple Roots Issue

It's possible that having several roots in your application will result in an error. "No profiling data has been recorded for the selected root," the Profiler may indicate. To see if any data has been captured for this problem, you must select a different root.

  • Render the Thresholds

When a commit is extraordinarily fast, performance.now() provides no useful timing information to the Profiler.

 

2. How to profile a React component?

Ans: By right-clicking anywhere on the website and selecting "Inspect," you can access the browser developer tools. After that, go to the "Profiler" tab. This is the React DevTools profiler, and you can now "Start profiling" the application by clicking the small blue circle.

From here, explore around with the application a little. You can create a new user account. Then, to "Stop profiling", click the small red circle.

Key Takeaways

In this blog, we went over the fundamentals of React Profiler. Both the React Profiler component and the React Profiler DevTool are excellent and may be used in cooperation with one another. 

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React profiler in Web Development. 

Credits: GIPHY

Happy Developing!

Live masterclass