Passing Core Web Vitals in a React app: what moves LCP
How to find the element that sets your LCP, ship less before the first paint with code splitting, preload only what matters, and measure the change properly.
By M. Adnan Saleem · · Updated · 7 min read
On Qatar's national event platforms I brought core pages to Core Web Vitals compliance through memoization, virtualization, lazy loading and code splitting, which improved LCP by about 35% and TTI by about 30%. On a payments platform, dynamic code splitting cut the initial bundle by about 35%. The method is the same every time, and it starts with measuring, not with optimizing.
The three numbers
- LCP (Largest Contentful Paint): when the biggest visible element appears. Good is 2.5 seconds or less.
- INP (Interaction to Next Paint): how long the page takes to respond to a tap or key press. Good is 200 milliseconds or less.
- CLS (Cumulative Layout Shift): how much the page jumps while loading. Good is 0.1 or less.
Google judges these on real visits at the 75th percentile, so a fast laptop on office wifi tells you very little. Test with mobile emulation and a throttled connection.
| Metric | Good | Needs improvement | Poor |
|---|---|---|---|
| LCP | 2.5 s or less | 2.5 s to 4 s | over 4 s |
| INP | 200 ms or less | 200 ms to 500 ms | over 500 ms |
| CLS | 0.1 or less | 0.1 to 0.25 | over 0.25 |
Find the LCP element first
Lighthouse and the Performance panel in Chrome both name the element that counts as the largest paint. Until you know which one it is, every optimization is a guess. It is usually a hero image or a headline, and the question is always the same: what has to download and run before that one element can appear?
LCP is four delays added together
The time to the largest paint breaks down into four parts, and each has a different fix:
- Time to first byte. How long the server takes to start answering. Fixed with caching, a CDN, or rendering on the server ahead of time.
- Resource load delay. The gap before the browser even starts fetching the LCP resource. Long when the image is only discovered after JavaScript runs.
- Resource load duration. The download itself. Fixed with smaller, better-compressed files.
- Element render delay. The resource has arrived but the page cannot paint it yet, usually because scripts or stylesheets are still blocking.
In a client-rendered React app the second and fourth parts are usually the large ones: nothing can be discovered or painted until the bundle has downloaded and run. That is why the next two sections matter most.
If the LCP element is an image
<!-- In the HTML itself, not added later by JavaScript, and never lazy-loaded -->
<img src="/hero.avif" width="1200" height="675" fetchpriority="high" alt="Stadium at night" />- Put it in the first HTML response. An image that React adds after hydration cannot start downloading until the JavaScript has finished.
- Mark it as high priority with
fetchpriority="high", and never give itloading="lazy". - Send the right size. Use
srcsetso a phone does not download a desktop image, and a modern format such as AVIF or WebP. - Set width and height so the space is reserved before the file arrives.
Ship less before the first paint
Most React apps send every screen to every visitor. Code splitting sends a screen only when it is opened:
// Before: the reports screen ships in the first bundle, to every visitor
import Reports from './Reports';
// After: it is downloaded only when someone opens it
const Reports = React.lazy(() => import('./Reports'));
<Suspense fallback={<ScreenSkeleton />}>
<Reports />
</Suspense>Split by route first, then split heavy pieces inside a route: charts, editors, maps, export dialogs. Anything below the fold or behind a click is a candidate.
Preload only what the first screen needs
Preloading is a promise that a file is urgent. Break that promise and the urgent files wait behind the others. This site is a small example: every page preloaded seven font files, four of which were used on one page each. Removing those four preloads took the Lighthouse mobile score from between 85 and 88 to 92 and cut the simulated LCP from about 4.1 seconds to 3.4, with no visible change.
Keep interactions cheap
INP suffers when one interaction re-renders too much. Two tools cover most cases. Memoization (React.memo, useMemo) stops components and calculations from repeating when their inputs did not change. Virtualization keeps long lists and tables down to the rows that are on screen.
When the work cannot be avoided, tell React which part is urgent. A transition lets the key press paint first and the heavy update follow:
const [isPending, startTransition] = useTransition();
function onChange(event) {
setText(event.target.value); // urgent: the field shows the key press
startTransition(() => setQuery(event.target.value)); // can wait: the results list
}Break up long tasks
An interaction is three parts: the input delay before your handler starts, the processing time of the handler, and the presentation delay until the next frame is painted. A handler that runs for 300 milliseconds blocks all three for every other interaction that arrives meanwhile. When the work cannot be made smaller, split it into chunks and hand control back to the browser between them:
async function applyFilters(rows, filters) {
for (const chunk of chunksOf(rows, 500)) {
processChunk(chunk, filters);
// Let the browser paint between chunks:
// scheduler.yield() where it exists, setTimeout elsewhere
if ('scheduler' in window && 'yield' in scheduler) await scheduler.yield();
else await new Promise((resolve) => setTimeout(resolve, 0));
}
}scheduler.yield() resumes your work as a prioritised task, ahead of other queued work, which a plain setTimeout does not. It is in Chrome from version 129 and Firefox from 142; Safari does not have it at the time of writing, hence the fallback. Large DOMs make the presentation part slow on their own, which is where virtualization and content-visibility come in.
Stop the page from jumping
Layout shift comes from content that arrives without reserved space: images, embeds, late banners, fonts that swap to a different width. Reserve the space up front:
/* The image box has its final size before the image arrives, so nothing jumps */
.hero-image { aspect-ratio: 16 / 9; width: 100%; }Measure before and after, the same way
- Run the same test three times before a change and three times after. Single runs vary too much to trust.
- Change one thing at a time, so you know what worked. I tried deferring hidden images on this site and it measured no gain, so it was dropped.
- Lab tools estimate. Real-user data, from the Chrome UX Report or your own analytics, is what Google uses, so confirm there once traffic allows.
Collect the numbers from real visits
Google's web-vitals library reports the same three metrics from your own users, so you do not have to wait for enough traffic to appear in the public data set:
import { onCLS, onINP, onLCP } from 'web-vitals';
const send = (metric) =>
navigator.sendBeacon('/vitals', JSON.stringify({ name: metric.name, value: metric.value, id: metric.id }));
onLCP(send);
onINP(send);
onCLS(send);The demo at the end of this article reads the same browser entries directly and shows them for the page you have open.
Store them with the page path and the device type. The pages that fail are rarely the ones the team tests every day, and the 75th percentile on mobile is usually far from what a developer laptop shows.
Where the time goes: attribution
A bad number on its own does not say what to fix. The library's attribution build splits each metric into the parts described above, and names the element involved:
import { onINP, onLCP } from 'web-vitals/attribution';
onLCP(({ value, attribution: a }) => {
// Which of the four delays is the big one?
send('LCP', value, {
element: a.target,
ttfb: a.timeToFirstByte,
loadDelay: a.resourceLoadDelay,
loadDuration: a.resourceLoadDuration,
renderDelay: a.elementRenderDelay,
});
});
onINP(({ value, attribution: a }) => {
// Which element, and was it the handler or the paint that was slow?
send('INP', value, {
element: a.interactionTarget,
type: a.interactionType,
inputDelay: a.inputDelay,
processing: a.processingDuration,
presentation: a.presentationDelay,
});
});With the LCP parts recorded, the fix is usually obvious: a large resourceLoadDelay means the image is discovered late, a large elementRenderDelay means scripts are blocking the paint. For INP, interactionTarget is a CSS selector for the element the user touched, which is how you find the one slow button among hundreds of fast ones.
In Next.js
Next.js wraps the same library. One client component in the root layout reports every metric:
// app/web-vitals.tsx
'use client';
import { useReportWebVitals } from 'next/web-vitals';
export function WebVitals() {
useReportWebVitals((metric) => {
navigator.sendBeacon('/vitals', JSON.stringify(metric));
});
return null;
}
// app/layout.tsx: render <WebVitals /> once inside <body>For the LCP image, the Image component adds the width, height and srcset for you. What it cannot guess is which image matters, so say so:
import Image from 'next/image';
// The hero: preloaded from <head>, never lazy.
// Next.js 16 calls this preload; earlier versions used priority
<Image
src="/hero.avif"
width={1200}
height={675}
preload
alt="Stadium at night"
/>Use it on one image per page, the one that is the largest paint on most viewports. Preloading several images puts them in a queue together, which is the font problem from earlier in a different costume.
Live demo
Try it live
The same metrics for the page you are on, read live from your browser. All five demos.
- –
- largest contentful paint
- –
- layout shift
- –
- slowest interaction
Measured in your browser on this visit, on your device and connection. Press the button and the slowest interaction passes 200 ms, the line Google draws for a good one. A dash means this browser does not report that metric.
Quick answers
The short version
What is a good LCP score?
2.5 seconds or less, measured at the 75th percentile of real visits. Between 2.5 and 4 seconds needs improvement, and above 4 seconds is poor.
Did INP replace FID?
Yes. Interaction to Next Paint replaced First Input Delay as a Core Web Vital in March 2024. It measures the whole interaction through to the next paint, not only the delay before the handler starts.
Does code splitting improve LCP?
It does when JavaScript is what delays the first paint, which is the usual case in a client-rendered React app. It does little if the LCP element is a slow image or the server response itself is slow.
What is a good INP score?
200 milliseconds or less at the 75th percentile of real visits. Up to 500 milliseconds needs improvement, and above 500 is poor.
How do I find which interaction has a bad INP?
Use the attribution build of the web-vitals library. Each INP report names the element that was interacted with and splits the time into input delay, processing duration and presentation delay.
How do I break up a long task in JavaScript?
Split the work into chunks and let the browser paint between them: await scheduler.yield() where it is supported (Chrome 129, Firefox 142), with a setTimeout fallback elsewhere.
Why is my Lighthouse score different from Search Console?
Lighthouse runs one simulated visit in a lab. Search Console reports what real Chrome users experienced over the previous 28 days. The field data is the one Google uses.
Keep reading
Related articles
- Rendering 20,000 rows in React without freezing the pageA reproducible React virtualization benchmark with 20,000 synthetic rows, raw runs, median filter delays, fixed-height windowing code and measurement limits.
- A real-time React dashboard that keeps up with WebSocketsWhy a live dashboard slows down over time, and the fixes: render once per frame, cap the list, aggregate as events arrive, and plan for reconnects.
- A React custom hooks library a team will actually useWhich hooks belong in a shared React library, useSyncExternalStore for browser state, useEffectEvent for stale closures, and testing hooks with renderHook.
The project behind this
Read the case study
What I built, where, and the numbers that came out of it.
Related experience: Frontend developer.