How to Avoid Expensive Calculations During Rendering :👈 👉:How to Investigate Slow React Page Loads

How to Improve Core Web Vitals in a React Application

How to Improve Core Web Vitals in a React Application

1. Introduction

Core Web Vitals are Google's user-experience metrics used to evaluate how well a website performs in terms of loading speed, interactivity, and visual stability.

For React applications, improving Core Web Vitals involves optimizing:

  • Initial page loading.
  • JavaScript execution.
  • Image loading.
  • Component rendering.
  • User interactions.
  • Layout stability.
  • API and server response times.

There are three main Core Web Vitals:

  1. LCP – Largest Contentful Paint: Measures loading performance.
  2. INP – Interaction to Next Paint: Measures responsiveness.
  3. CLS – Cumulative Layout Shift: Measures visual stability.

2. Core Web Vitals and Recommended Thresholds

Metric What It Measures Good Needs Improvement Poor
LCP Loading performance ≤ 2.5 seconds 2.5–4 seconds > 4 seconds
INP Interaction responsiveness ≤ 200 ms 200–500 ms > 500 ms
CLS Visual stability ≤ 0.1 0.1–0.25 > 0.25

Google evaluates these metrics at the 75th percentile of real user experiences, separately for mobile and desktop.

The target is to achieve good results for all three metrics.

3. Improve Largest Contentful Paint (LCP)

What is LCP?

LCP measures how long it takes for the largest visible content element in the viewport to render.

Typical LCP elements include:

  • Hero images.
  • Large banners.
  • Main headings.
  • Featured content images.
  • Large text blocks.

For example, consider a homepage with a large banner image. If that image takes five seconds to appear, the LCP score may be poor.

3.1 Optimize Images

Large images are a common reason for slow page loading.

Use modern image formats such as:

  • WebP
  • AVIF

Avoid unnecessarily large image files.

React example:

function Hero() {
    return (
        <img
            src="/images/hero.webp"
            alt="Main banner"
            width="1200"
            height="600"
            fetchPriority="high"
        />
    );
}

Important points:

  • Compress images.
  • Serve appropriately sized images.
  • Use responsive images with srcSet where appropriate.
  • Specify image dimensions.
  • Give the main above-the-fold image high loading priority.

Do not lazy-load the LCP image.

3.2 Lazy Load Images Below the Fold

Images that are not immediately visible should generally load when they approach the viewport.

function ProductImage({ product }) {
    return (
        <img
            src={product.image}
            alt={product.name}
            width="300"
            height="200"
            loading="lazy"
        />
    );
}

This reduces unnecessary initial network requests.

Important: Use lazy loading for below-the-fold images, not for the main image responsible for LCP.

3.3 Reduce JavaScript Bundle Size

React applications can have large JavaScript bundles containing code that is not immediately required.

Large bundles increase downloading, parsing, compilation, and execution time.

Techniques:

  • Remove unused dependencies.
  • Use tree shaking.
  • Apply code splitting.
  • Lazy-load routes and components.
  • Avoid unnecessarily large libraries.
  • Analyze production bundles.

Example using React.lazy:

import { lazy, Suspense } from "react";
const Dashboard = lazy(
    () => import("./Dashboard")
);
function App() {
    return (
        <Suspense fallback={<p>Loading...</p>}>
            <Dashboard />
        </Suspense>
    );
}

The Dashboard component is loaded when React needs to render it instead of being included in the initial application bundle.

3.4 Use a CDN

A Content Delivery Network distributes static resources across geographically distributed servers.

Examples of resources:

  • Images.
  • JavaScript bundles.
  • CSS files.
  • Fonts.
  • Videos.

A CDN can reduce network latency by serving resources from a location closer to the user.

3.5 Improve Server Response Time

Even an optimized React application can load slowly if the server takes too long to respond.

Improve backend performance by:

  • Optimizing database queries.
  • Adding appropriate database indexes.
  • Using server-side caching.
  • Reducing unnecessary API calls.
  • Enabling HTTP compression.
  • Using efficient hosting infrastructure.

For an ASP.NET Core backend, use asynchronous operations for I/O-bound work and avoid unnecessary database queries.

3.6 Reduce Render-Blocking Resources

Resources that prevent the browser from rendering content can delay LCP.

Consider:

  • Removing unused CSS.
  • Deferring non-critical JavaScript.
  • Loading non-critical scripts asynchronously where appropriate.
  • Avoiding unnecessary third-party scripts.
  • Prioritizing critical resources.

4. Improve Interaction to Next Paint (INP)

What is INP?

INP measures how responsive a page is when users interact with it.

It considers interactions such as:

  • Clicking buttons.
  • Typing into input fields.
  • Selecting dropdown values.
  • Opening menus.
  • Submitting forms.

A good INP score is 200 milliseconds or less.

4.1 Avoid Long-Running JavaScript Tasks

Long-running JavaScript operations can block the browser's main thread.

Example of a potentially expensive calculation:

function ProductList({ products }) {
    const filteredProducts = products.filter(
        product => product.price > 1000
    );
    return (
        <ul>
            {filteredProducts.map(product => (
                <li key={product.id}>
                    {product.name}
                </li>
            ))}
        </ul>
    );
}

For very large datasets, repeated filtering and sorting may become expensive.

Use appropriate optimizations:

  • useMemo for expensive derived calculations.
  • Efficient algorithms.
  • Server-side filtering for large datasets.
  • Web Workers for suitable CPU-intensive tasks.

4.2 Use useMemo for Expensive Calculations

import { useMemo } from "react";
function ProductList({ products }) {
    const filteredProducts = useMemo(() => {
        return products.filter(
            product => product.price > 1000
        );
    }, [products]);
    return (
        <ul>
            {filteredProducts.map(product => (
                <li key={product.id}>
                    {product.name}
                </li>
            ))}
        </ul>
    );
}

This avoids repeating the filtering calculation when the products reference has not changed.

4.3 Use useTransition for Non-Urgent Updates

React provides useTransition to mark certain state updates as non-urgent.

This is useful when an interaction triggers an expensive rendering update.

import { useState, useTransition } from "react";
function SearchProducts({ products }) {
    const [search, setSearch] = useState("");
    const [filteredSearch, setFilteredSearch] = useState("");
    const [isPending, startTransition] = useTransition();
    function handleSearch(event) {
        const value = event.target.value;
        setSearch(value);
        startTransition(() => {
            setFilteredSearch(value);
        });
    }
    const filteredProducts = products.filter(product =>
        product.name.toLowerCase().includes(
            filteredSearch.toLowerCase()
        )
    );
    return (
        <>
            <input
                value={search}
                onChange={handleSearch}
                placeholder="Search products"
            />
            {isPending && <p>Updating...</p>}
            <ul>
                {filteredProducts.map(product => (
                    <li key={product.id}>
                        {product.name}
                    </li>
                ))}
            </ul>
        </>
    );
}

The input update remains urgent, while the filtering-related state update is marked as non-urgent.

Important: useTransition does not make the filtering algorithm faster. It helps React schedule rendering work more appropriately.

4.4 Debounce Search Requests

When users type into a search box, avoid sending an API request for every keystroke.

Debouncing waits until the user pauses typing before executing the search.

import { useEffect, useState } from "react";
function SearchProducts() {
    const [search, setSearch] = useState("");
    const [debouncedSearch, setDebouncedSearch] = useState("");
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedSearch(search);
        }, 400);
        return () => clearTimeout(timer);
    }, [search]);
    useEffect(() => {
        if (!debouncedSearch.trim()) {
            return;
        }
        console.log("Call API:", debouncedSearch);
    }, [debouncedSearch]);
    return (
        <input
            value={search}
            onChange={event => setSearch(event.target.value)}
            placeholder="Search products"
        />
    );
}

This reduces unnecessary API requests and backend processing.

4.5 Use Web Workers for Heavy Calculations

For CPU-intensive operations, Web Workers can move suitable calculations away from the browser's main thread.

Examples:

  • Large data processing.
  • Complex mathematical calculations.
  • File processing.
  • Data transformations.

This helps keep the interface responsive while background work is running.

4.6 Avoid Unnecessary Component Rendering

Use React performance techniques appropriately:

Technique Purpose
React.memo Avoid unnecessary child component renders when props are unchanged.
useMemo Cache expensive calculation results.
useCallback Cache function references when useful.
React Compiler Automatically optimize eligible React code.
Virtualization Render only the visible portion of large lists.

Do not apply memoization everywhere. Profile the application and optimize genuine bottlenecks.

4.7 Reduce DOM Complexity

Large DOM trees can increase browser layout and rendering work.

Improve performance by:

  • Rendering only necessary elements.
  • Using pagination.
  • Applying virtualization to large lists.
  • Avoiding deeply nested unnecessary elements.
  • Keeping component updates focused.

5. Improve Cumulative Layout Shift (CLS)

What is CLS?

CLS measures unexpected movement of visible page elements while the page is loading or being used.

For example:

  1. A user starts reading an article.
  2. An image loads without reserved space.
  3. The content below it moves downward.
  4. The user loses their reading position.

This creates a poor user experience.

A good CLS score is 0.1 or less.

5.1 Specify Image Dimensions

Always reserve the required image space.

Incorrect:

<img src="/images/product.webp" alt="Product" />

Correct:

<img
    src="/images/product.webp"
    alt="Product"
    width="400"
    height="300"
/>

Alternatively, use an appropriate CSS aspect-ratio rule.

This allows the browser to reserve space before the image loads.

5.2 Reserve Space for Advertisements

Advertisements can cause layout shifts when they load dynamically.

Reserve space for the advertisement container.

function Advertisement() {
    return (
        <div className="ad-container">
            Advertisement
        </div>
    );
}

The corresponding layout should reserve an appropriate height or aspect ratio for the expected advertisement.

5.3 Reserve Space for Dynamic Content

API responses may cause content to appear after the initial page layout.

Avoid allowing new content to unexpectedly push existing content around.

function UserProfile({ user, loading }) {
    return (
        <section>
            {loading ? (
                <div className="profile-placeholder">
                    Loading profile...
                </div>
            ) : (
                <div>
                    <h2>{user.name}</h2>
                    <p>{user.email}</p>
                </div>
            )}
        </section>
    );
}

The placeholder should have dimensions similar to the final content.

5.4 Avoid Inserting Content Above Existing Content

Avoid inserting banners, notifications, or dynamically loaded content above content that users are already viewing.

For example, if a notification appears at the top of an article and pushes the article downward, it may contribute to CLS.

Reserve space or use a presentation that does not unexpectedly shift the existing layout.

5.5 Use Stable Font Loading

Custom fonts can cause text to change size or wrap differently after loading.

To reduce layout shifts:

  • Use optimized font files.
  • Prefer WOFF2 where appropriate.
  • Preload important fonts when justified.
  • Use suitable fallback fonts.
  • Consider font-display: swap.
  • Choose fallback fonts with similar metrics.

Example:

<link
    rel="preload"
    href="/fonts/app-font.woff2"
    as="font"
    type="font/woff2"
    crossorigin
>

Do not preload every font. Prioritize only fonts needed for the initial visible content.

5.6 Prefer Transform Animations

Animations that change layout properties can cause unnecessary layout calculations.

Prefer transform and opacity for animations where appropriate.

Examples:

  • transform: translateY()
  • transform: scale()
  • opacity

Avoid frequently animating layout-affecting properties such as top, left, width, and height when a transform-based alternative is suitable.

6. Optimize React Application Loading

Beyond the three individual metrics, improve the overall loading experience.

6.1 Use Code Splitting

Split large applications into smaller chunks.

import { lazy, Suspense } from "react";
const Reports = lazy(
    () => import("./Reports")
);
function App() {
    return (
        <Suspense fallback={<p>Loading reports...</p>}>
            <Reports />
        </Suspense>
    );
}

Load features when they are required rather than downloading all application code initially.

6.2 Optimize Route-Based Loading

For large applications, load route components when users navigate to them.

import { lazy, Suspense } from "react";
import { Routes, Route } from "react-router-dom";
const Home = lazy(() => import("./Home"));
const Dashboard = lazy(() => import("./Dashboard"));
const Reports = lazy(() => import("./Reports"));
function App() {
    return (
        <Suspense fallback={<p>Loading page...</p>}>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/reports" element={<Reports />} />
            </Routes>
        </Suspense>
    );
}

This prevents all route components from being required in the initial JavaScript bundle.

6.3 Use Caching

Cache suitable static resources and API responses.

Examples:

  • Browser caching.
  • CDN caching.
  • Service Worker caching.
  • Backend response caching.
  • React Query or similar data-fetching cache libraries.

Caching reduces repeated network requests and can improve subsequent navigation.

Use appropriate cache invalidation and freshness policies, especially for frequently changing data.

6.4 Optimize Third-Party Scripts

Third-party scripts can affect loading and responsiveness.

Examples:

  • Analytics.
  • Advertising scripts.
  • Chat widgets.
  • Social media integrations.
  • Tracking tools.

Review whether every script is necessary.

Load non-critical scripts without blocking initial rendering where possible.

7. Measure Core Web Vitals

Performance optimization should be based on measurements rather than assumptions.

7.1 Google PageSpeed Insights

Google PageSpeed Insights

Provides:

  • Core Web Vitals results.
  • Mobile and desktop performance.
  • Lab performance diagnostics.
  • Field data when available.
  • Optimization recommendations.

7.2 Google Search Console

Google Search Console

The Core Web Vitals report helps identify groups of URLs that need improvement based on real user data.

7.3 Chrome Lighthouse

Available through Chrome DevTools.

It provides performance audits and recommendations for:

  • LCP.
  • CLS.
  • JavaScript execution.
  • Image optimization.
  • Render-blocking resources.
  • Unused JavaScript.

Lighthouse does not directly measure field INP because it does not reproduce real user interaction. Total Blocking Time (TBT) is a useful lab diagnostic, but it is not a replacement for field INP.

7.4 React Developer Tools Profiler

Use the React Profiler to identify:

  • Components rendering unnecessarily.
  • Expensive component rendering.
  • Repeated updates.
  • Performance bottlenecks.

8. Measure Real User Experience with web-vitals

The web-vitals library allows you to collect Core Web Vitals from actual users.

Install the package:

npm install web-vitals

Create a file named reportWebVitals.js:

import {
    onCLS,
    onINP,
    onLCP
} from "web-vitals";
function sendToAnalytics(metric) {
    const body = JSON.stringify(metric);
    if (navigator.sendBeacon) {
        navigator.sendBeacon(
            "/api/performance",
            body
        );
    } else {
        fetch("/api/performance", {
            method: "POST",
            body,
            headers: {
                "Content-Type": "application/json"
            },
            keepalive: true
        });
    }
}
onCLS(sendToAnalytics);
onINP(sendToAnalytics);
onLCP(sendToAnalytics);

Call this function once during application startup:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
reportWebVitals();
createRoot(document.getElementById("root")).render(
    <StrictMode>
        <App />
    </StrictMode>
);

The backend can store these metrics for analysis.

For production use, also consider:

  • Recording the page URL.
  • Recording device and connection information where appropriate.
  • Aggregating results by page and device category.
  • Respecting user privacy and applicable consent requirements.
  • Monitoring the 75th percentile instead of relying only on averages.

9. Practical Optimization Checklist

Area Optimization Expected Benefit
Images Compress and use WebP/AVIF Better LCP
Main banner Prioritize the LCP image Better LCP
Other images Lazy-load below-the-fold images Better loading performance
JavaScript Reduce bundle size Better LCP and INP
Code splitting Load features when needed Better initial loading
React rendering Avoid unnecessary updates Better INP
Calculations Use efficient algorithms and useMemo when appropriate Better INP
Search Debounce API requests Reduced unnecessary work
Heavy processing Use Web Workers where appropriate Better INP
Images and ads Reserve layout space Better CLS
Fonts Optimize font loading Better LCP and CLS
API Optimize backend and database queries Better LCP
CDN Serve static assets closer to users Better LCP
DOM Reduce unnecessary elements Better INP

10. Common Mistakes to Avoid

  1. Lazy-loading the main hero image: This can delay LCP. Prioritize the LCP image instead.
  2. Using large JavaScript libraries unnecessarily: This increases download, parsing, and execution costs.
  3. Applying useMemo everywhere: Memoization is not automatically beneficial for every calculation.
  4. Ignoring mobile performance: Mobile devices and networks may have more limited resources.
  5. Not specifying image dimensions: This can cause layout shifts.
  6. Loading too many third-party scripts: They can consume network and main-thread resources.
  7. Measuring only in development: Development builds can behave differently from production builds.
  8. Relying only on Lighthouse: Lab testing is useful, but real-user field data is essential.
  9. Optimizing only the homepage: Other important pages may have different performance problems.
  10. Ignoring backend performance: Slow APIs and database queries can delay visible content.

11. How to Prioritize Improvements

When improving Core Web Vitals in an existing React application, follow this order:

  1. Measure: Use PageSpeed Insights, Lighthouse, and Search Console to identify actual problems.
  2. Identify LCP issues: Check the main image, server response time, and render-blocking resources.
  3. Identify INP issues: Check long JavaScript tasks, expensive calculations, and unnecessary rendering.
  4. Identify CLS issues: Check images, advertisements, fonts, and dynamically inserted content.
  5. Optimize: Apply the most relevant improvements rather than changing everything.
  6. Test: Re-run lab measurements and compare results.
  7. Monitor: Collect real-user metrics after deployment.

12. Interview Questions and Answers

Q1. What are Core Web Vitals?

Core Web Vitals are Google's user-experience metrics that measure loading performance, responsiveness, and visual stability. The three metrics are LCP, INP, and CLS.

Q2. What is the difference between LCP and FCP?

First Contentful Paint (FCP) measures when the first content appears on the screen. Largest Contentful Paint (LCP) measures when the largest relevant visible content element is rendered.

Q3. Why is INP important?

INP measures how quickly a page responds visually to user interactions. A poor INP can make an application feel slow even when the page has loaded.

Q4. How can React applications improve LCP?

Optimize the main visible image, reduce JavaScript bundle size, use code splitting, improve server response time, prioritize critical resources, and use a CDN.

Q5. How can React applications improve INP?

Avoid long-running JavaScript tasks, reduce unnecessary component rendering, optimize calculations, use Web Workers for suitable heavy operations, and minimize unnecessary third-party scripts.

Q6. How can React applications improve CLS?

Specify image dimensions, reserve space for advertisements and dynamic content, optimize font loading, and avoid unexpected insertion of content above existing content.

Q7. Does React.memo improve Core Web Vitals?

React.memo can reduce unnecessary component rendering. When those renders contribute to interaction delays, it may help improve INP. It does not directly guarantee better Core Web Vitals scores.

Q8. What is the difference between lab data and field data?

Lab data is collected in a controlled testing environment. Field data represents actual user experiences across different devices, networks, and interactions.

Q9. Why is Lighthouse not enough to measure INP?

Lighthouse performs automated tests without reproducing the full range of real user interactions. It uses Total Blocking Time as a diagnostic indicator, while field measurement is needed to evaluate actual INP.

Q10. How do you monitor Core Web Vitals in production?

Use the web-vitals library to collect LCP, INP, and CLS measurements and send them to an analytics endpoint. Analyze the 75th percentile of real-user data.

13. Key Takeaways

  • LCP: Focus on images, server response time, critical resources, and JavaScript bundle size.
  • INP: Focus on responsiveness, efficient JavaScript, and avoiding unnecessary rendering.
  • CLS: Focus on layout stability, image dimensions, fonts, and dynamic content.
  • Use code splitting and lazy loading to reduce initial loading work.
  • Optimize both frontend and backend performance.
  • Measure performance on mobile and desktop.
  • Use field data to understand actual user experiences.
  • Optimize based on measurements rather than assumptions.

Golden Rule: A fast React application is not just one that loads quickly. It must also respond quickly to user interactions and maintain a stable layout while users interact with it.

🔙
How to Avoid Expensive Calculations During Rendering :👈 👉:How to Investigate Slow React Page Loads

Comments and Discussion