Understanding Web Vitals in React: A Guide to Improving User Experience and performance.
Tags: react, webvitals, ux, optimizingreactapps
Published: 2023-01-09 08:46:43

As developers, it's our responsibility to create web applications that offer a seamless and enjoyable experience for our users. This is especially important given that the success of a web app is largely determined by its ability to meet the needs and preferences of its users. However, it can be difficult to gauge the user experience (UX) of an app during the development process, as the way it functions during this phase may differ from how users actually interact with it. That's where web vitals come in. In this article, we will discuss what web vitals are and how to measure and report them in React applications.

## What are web vitals?

Web vitals are a set of metrics that measure the performance and user experience of a web page. They are designed to provide developers with a common set of metrics to focus on, in order to improve the overall user experience of their web pages. The three main web vitals are:

1. **Largest Contentful Paint (LCP)**: measures the loading performance of a page, by recording the time it takes for the largest image or text block to load.

2. **First Input Delay (FID)**: measures the interactivity of a page, by recording the time it takes for a page to become responsive to user input.

3. **Cumulative Layout Shift (CLS)**: measures the stability of a page, by recording the amount of layout shift that occurs during the loading process.

Web vitals are an important part of the user experience because they measure the key aspects of a web page that affect how users perceive and interact with it. By focusing on these metrics, developers can ensure that their web pages are fast, responsive, and stable, which can help to improve user satisfaction and engagement.

## Measuring web vitals in react apps

By default, Create React App includes a performance relayer that allows you to measure and analyze the performance of your application using different metrics.

To measure any of the supported metrics, you only need to pass a function into the reportWebVitals function in `index.js:`

```
reportWebVitals(console.log);
```

In Create React App, a third-party library is used to measure these metrics ([web-vitals](https://github.com/GoogleChrome/web-vitals)). The library supports all of the [Core Web Vitals](https://web.dev/vitals/#core-web-vitals) as well as a number of other metrics that are useful in diagnosing real-user performance issues.

Below is the object returned to the function when a metric value is calculated. 

```
interface Metric {
  /**
   * The name of the metric (in acronym form).
   */
  name: 'CLS' | 'FCP' | 'FID' | 'INP' | 'LCP' | 'TTFB';

  /**
   * The current value of the metric.
   */
  value: number;

  /**
   * The rating as to whether the metric value is within the "good",
   * "needs improvement", or "poor" thresholds of the metric.
   */
  rating: 'good' | 'needs-improvement' | 'poor';

  /**
   * The delta between the current value and the last-reported value.
   * On the first report, `delta` and `value` will always be the same.
   */
  delta: number;

  /**
   * A unique ID representing this particular metric instance. This ID can
   * be used by an analytics tool to dedupe multiple values sent for the same
   * metric instance, or to group multiple deltas together and calculate a
   * total. It can also be used to differentiate multiple different metric
   * instances sent from the same page, which can happen if the page is
   * restored from the back/forward cache (in that case new metrics object
   * get created).
   */
  id: string;

  /**
   * Any performance entries relevant to the metric value calculation.
   * The array may also be empty if the metric value was not based on any
   * entries (e.g. a CLS value of 0 given no layout shifts).
   */
  entries: (
    | PerformanceEntry
    | LayoutShift
    | FirstInputPolyfillEntry
    | NavigationTimingPolyfillEntry
  )[];

  /**
   * The type of navigation.
   *
   * This will be the value returned by the Navigation Timing API (or
   * `undefined` if the browser doesn't support that API), with the following
   * exceptions:
   * - 'back-forward-cache': for pages that are restored from the bfcache.
   * - 'prerender': for pages that were prerendered.
   * - 'restore': for pages that were discarded by the browser and then
   * restored by the user.
   */
  navigationType:
    | 'navigate'
    | 'reload'
    | 'back-forward'
    | 'back-forward-cache'
    | 'prerender'
    | 'restore';
}
```


## Sending results to analytics

With the `reportWebVitals` function, you can send any of results to an analytics endpoint to measure and track real user performance on your site. For example:

```
function sendToAnalytics(metric) {
  const body = JSON.stringify(metric);
  const url = 'https://example.com/analytics';

  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body);
  } else {
    fetch(url, { body, method: 'POST', keepalive: true });
  }
}

reportWebVitals(sendToAnalytics);

```
[_More on this_](https://create-react-app.dev/docs/measuring-performance#sending-results-to-analytics)

In this article, we learned about web vitals, which are a set of metrics that measure the performance and user experience of a web page. The three main web vitals are Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS). By focusing on these metrics, developers can ensure that their web pages are fast, responsive, and stable, which can help to improve user satisfaction and engagement. We also discussed how to measure and report web vitals in React applications using the Create React App performance relayer and the web-vitals library. By incorporating web vitals into your development process, you can improve the UX of your web app and better meet the needs of your users.