← All posts

Fix LCP, CLS, and INP in Your React App: A Hands‑On Guide

Learn how to pre‑load images, reserve layout space, and defer heavy work in React to slash LCP, CLS, and INP scores and boost real‑world UX.

A sluggish React single‑page app can feel like a broken promise: the headline loads, the user scrolls, but the page keeps moving, the main image never appears fast enough, and every click feels like it’s happening in slow motion.
Fixing these symptoms isn’t about adding a new library; it’s about understanding the three Core Web Vitals that Google uses to gauge real‑world experience and applying a handful of proven code patterns in your component tree.


TL;DR

  • LCP – Preload critical images, set width/height, and extract critical CSS.
  • CLS – Reserve layout space for dynamic content; use aspect-ratio or placeholder elements.
  • INP – Defer heavy work with React.lazy, Suspense, requestIdleCallback, or Web Workers.
  • A single, reusable component that demonstrates all three fixes keeps the codebase clean and the metrics in check.

1. Understanding Core Web Vitals: LCP, CLS, and INP – What They Really Mean

  • LCP (Largest Contentful Paint) measures the time until the largest text or image block is visible.
  • CLS (Cumulative Layout Shift) tracks visual stability by summing all layout shifts that occur after the page starts loading.
  • INP (Interaction to Next Paint) evaluates responsiveness over the entire session, not just the first interaction.

Google’s thresholds (LCP < 2.5 s, CLS < 0.1, INP > 200 ms) are guidelines; the real goal is to keep these numbers improving over time. They complement classic metrics like First Contentful Paint (FCP) and Total Blocking Time (TBT), giving a fuller picture of user experience.


2. The Real Cost of Poor LCP: Why 2.5 s Matters in Modern UX

  • A slow LCP keeps the user staring at a blank screen, which increases bounce rates and reduces conversion.
  • Large images, uncompressed fonts, and blocking CSS are the most common culprits.
  • Server response time and network latency can push LCP beyond 2.5 s, especially on mobile.
  • Chrome DevTools or Lighthouse provide a clear view of which resources delay the paint.
  • Optimizing LCP often involves image compression, critical CSS extraction, and server‑side rendering (SSR).

In practice, a 1 s improvement in LCP can raise conversion rates by a few percent on e‑commerce sites, making it a high‑impact target for every developer.


3. CLS: The Invisible Friction That Breaks Layout Stability

  • Layout shifts happen when elements change position after rendering begins.
  • Missing width/height attributes on images, dynamic ad slots, and late‑loaded fonts trigger shifts.
  • CLS accumulates over the entire page lifecycle; even a single large shift can push the score past the acceptable range.
  • Pre‑allocating space with CSS or using placeholder elements keeps the layout stable.
  • Chrome’s Layout Shift inspection panel pinpoints the offending elements.

A classic example is an image that loads after the page has rendered, causing text to jump. The fix is simply to set explicit dimensions or use a CSS aspect‑ratio box.


4. INP: Measuring Interactivity Beyond First Input Delay

  • INP tracks all user‑initiated events and the time until the next paint, providing a holistic view of responsiveness.
  • Heavy JavaScript bundles, synchronous rendering, and blocking main‑thread work inflate INP.
  • Unlike FID, which only looks at the first click, INP reflects user experience across the entire session.
  • Measuring INP requires a recent browser version or a custom implementation with the PerformanceObserver API.
  • Improving INP often means deferring non‑critical work, using requestIdleCallback, or moving logic to Web Workers.

In a real‑world SPA, a heavy analytics script that runs on every route change can easily push INP beyond 200 ms, turning a smooth interaction into a sluggish one.


5. Hands‑On Fixes: Code Patterns for LCP, CLS, and INP in React

Below is a reusable component that ties together all three core fixes. It preloads a hero image, reserves space to avoid CLS, and defers a heavy chart rendering until the main paint is complete.

// HeroWithChart.jsx
import { useEffect, useState, Suspense, lazy } from 'react';

// Lazy‑load the heavy chart component
const HeavyChart = lazy(() => import('./HeavyChart'));

export default function HeroWithChart({ imageSrc, alt }) {
  // State to trigger chart rendering after initial paint
  const [chartVisible, setChartVisible] = useState(false);

  // Defer heavy work until the main thread is idle
  useEffect(() => {
    const idleCallback = requestIdleCallback(() => {
      // Small delay to ensure LCP has finished
      setChartVisible(true);
    });
    return () => cancelIdleCallback(idleCallback);
  }, []);

  return (
    <section className="hero">
      {/* Preload critical image */}
      <link rel="preload" as="image" href={imageSrc} />

      {/* Reserve space for the image to avoid CLS */}
      <img
        src={imageSrc}
        alt={alt}
        width={1200}
        height={600}
        loading="eager"
        className="hero-image"
      />

      {/* The chart appears after LCP and initial paint */}
      {chartVisible && (
        <Suspense fallback={<div className="chart-placeholder" />}>
          <HeavyChart />
        </Suspense>
      )}
    </section>
  );
}

What the code does

Pattern LCP CLS INP
<link rel="preload"> Signals the browser to fetch the hero image early, reducing paint time — —
width/height on <img> Provides intrinsic dimensions so the browser can reserve space before the image loads ✔️ Prevents the image from pushing content down when it finally arrives —
requestIdleCallback + useEffect Keeps the main thread free for the initial paint — Defers heavy work that would otherwise block subsequent interactions
React.lazy + Suspense Loads the chart component only after the hero image has painted ✔️ The placeholder keeps layout stable until the chart is ready Avoids blocking the main thread during heavy rendering

Why loading="eager"?

By default, browsers defer image loading until it’s needed. For the hero image, we want it to load as soon as possible because it contributes to LCP. Setting loading="eager" overrides the default and forces early download.

Why requestIdleCallback?

Heavy scripts that run synchronously after the paint can delay the next paint for any user interaction. requestIdleCallback tells the browser to run the callback when the main thread is idle, ensuring that the user’s first interaction feels immediate.

Why Suspense?

React’s Suspense placeholder keeps the DOM from shifting when the heavy chart finally loads. The placeholder can be a simple spinner or a gray block that matches the chart’s dimensions, preventing CLS.


6. Common Pitfalls and Trade‑Offs When Tuning Core Web Vitals

Pitfall Impact Mitigation
Over‑preloading many resources Wastes bandwidth and can actually slow LCP by saturating the connection Preload only the most critical assets (hero images, fonts, critical CSS).
Deferring all third‑party scripts Breaks analytics, ads, or essential functionality Load them asynchronously with async or defer, and only defer non‑critical ones.
Adding explicit dimensions to every image Increases markup size and maintenance overhead Use a CSS helper (e.g., aspect-ratio) or a wrapper component to keep the markup DRY.
Aggressively using requestIdleCallback Delays critical interactions if the idle period is long Combine with a minimum timeout fallback or use setTimeout with a short delay as a safety net.
Optimizing LCP at the expense of CLS A larger hero image with no dimensions can improve LCP but cause a shift Always pair LCP fixes with CLS‑safe markup (explicit width/height or aspect‑ratio).

Trade‑offs are inevitable. For example, increasing the hero image size may improve LCP but risk a larger CLS if the image is not dimensioned. The key is to measure, iterate, and keep both metrics in sight.


Real‑World Example: E‑Commerce Product Page

An e‑commerce product page often has:

  1. A large hero image of the product.
  2. A dynamic “Add to Cart” button that loads a third‑party cart widget.
  3. A reviews section that renders a heavy chart.

Fixes applied:

  • Hero image: Preloaded, sized, and set to loading="eager".
  • Cart widget: Loaded asynchronously after the main paint with async and defer.
  • Reviews chart: Lazy‑loaded via React.lazy and wrapped in Suspense.
  • Font loading: Critical fonts extracted into a small CSS chunk and preloaded.

Result: LCP dropped from 3.2 s to 1.8 s, CLS fell below 0.05, and INP improved from 350 ms to 120 ms, leading to a measurable uptick in conversion.


Key Takeaways

  • LCP: Preload critical images, set intrinsic dimensions, and extract critical CSS.
  • CLS: Reserve layout space for all dynamic content; use explicit sizes or CSS placeholders.
  • INP: Defer non‑critical JavaScript with React.lazy, Suspense, requestIdleCallback, or Web Workers.
  • A single, reusable component that bundles these patterns keeps your codebase maintainable and your Core Web Vitals in check.
  • Measure, iterate, and balance the three metrics; a trade‑off in one area can be mitigated by improvements in another.

By tying each Core Web Vital to concrete, actionable code patterns, you eliminate the guesswork and give your React SPA a measurable, user‑centric performance boost.

FAQ

What is the threshold for LCP according to Google?

Google recommends an LCP score below 2.5 seconds to provide a good user experience.

How does requestIdleCallback help with INP?

requestIdleCallback schedules non‑critical work to run when the main thread is idle, preventing heavy scripts from blocking user interactions and keeping INP low.

Why should I set width and height on images?

Setting explicit width and height reserves layout space, preventing cumulative layout shift and ensuring a stable visual experience.

What role does React.lazy play in LCP?

React.lazy defers loading of large components until after the critical content has painted, reducing the time to first contentful paint and improving LCP.