Diagnosing INP: Long Tasks and Re-renders
Read an interaction from Event Timing and long-task entries, cut the handler down with scheduler.yield, and stop a framework from re-rendering work the visitor never asked for.
Contentsand lesson path
On this page
- The problem: a button that freezes the page
- Step 1: watch the interaction in the page
- Step 2: paint first, then yield
- Step 3: when the framework re-renders too much
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Performance & Core Web Vitals
- Field Data: Web Vitals, Client Errors and Real-User Monitoring Concept · 25 min
- Diagnosing LCP: Images, Fonts and the Critical Path Worked example · 25 min
- Diagnosing INP: Long Tasks and Re-renders Worked example · 25 min
- Shipping Less JavaScript: Bundle Analysis and Splitting Worked example · 20 min
- Lab: Profile, Fix and Budget a Slow Storefront Lab · 30 min
- Check: Diagnose the Trace Knowledge check · 10 questions
What you will learn
- Improve responsiveness by breaking up long tasks, deferring non-critical work and removing unnecessary React re-renders, verified with the Performance panel and React Profiler.
Prerequisites: How Browsers Render Pages
01. The problem: a button that freezes the page
A settings page has an innocent-looking "Save settings" button. Its handler validates the whole form, updates a status line, then sends analytics and writes to storage — all synchronously. On the lab machine the tap feels sticky; on a mid-range phone it feels broken. Interaction to Next Paint (INP) exists for exactly this: it reports, for the worst interactions of a visit, the time from the tap or key to the next painted frame. Under 200 ms at the 75th percentile is good; over 500 ms is poor.
INP is a field metric, so the diagnosis starts in the browser with the two entry types that describe an interaction: Event Timing entries for the interaction itself and long-task entries for any chunk of main-thread work over 50 ms — the same long tasks you met in the main-thread lesson.
02. Step 1: watch the interaction in the page
Here is the handler. blockFor(ms) is a busy-wait that stands in for real synchronous work, such as validation or a storage write:
save.addEventListener('click', () => {
blockFor(35); // validate the form
status.textContent = 'Saved'; // the visible update
blockFor(280); // analytics, storage, the rest
});Two PerformanceObservers record the story: Event Timing shows what the visitor waited (its duration runs to the next paint, so it is the INP contribution for that interaction), and long-task entries show what the handler did to the main thread. The observers below ran in a headless Chromium 156 page (Playwright 1.64.1) while a script clicked the button:
const events = [];
const tasks = [];
new PerformanceObserver((list) => events.push(...list.getEntries()))
.observe({ type: 'event', buffered: true, durationThreshold: 16 });
new PerformanceObserver((list) => tasks.push(...list.getEntries()))
.observe({ type: 'longtask', buffered: true });
// after clicking Save settings:
const click = events.filter((e) => e.name === "click").at(-1);
console.log("click duration", Math.round(click.duration), "ms");
for (const t of tasks) {
console.log("long task at", Math.round(t.startTime), "ms, for",
Math.round(t.duration), "ms");
}click duration 320 ms
long task at 1113 ms, for 317 msOne tap produced one 317 ms task (the 315 ms of busy-waiting plus the handler's own work) and a 320 ms wait for the next paint — in the needs-improvement band (over 200 ms; poor starts at 500 ms). The web-vitals attribution build splits the same wait into three sub-parts, and its beacon for the storefront's "Add to cart" (which blocks the same way) read inputDelay: 1, processingDuration: 425, presentationDelay: 7. Nearly everything is processing duration: the handler itself. Input delay and presentation delay would point elsewhere — a busy main thread before the handler runs, or heavy rendering after it.
A long-task entry says that the thread was busy, not which script kept it busy. Chromium (since version 123; Firefox and Safari do not ship it) also reports Long Animation Frames (long-animation-frame entries), whose scripts list names the source URL, function and duration of each long script in the frame. The web-vitals attribution build attaches the frames that overlap the INP interaction as longAnimationFrameEntries, which is how a field beacon can name the slow script without a profiler.
03. Step 2: paint first, then yield
The visitor judges the tap by the next paint, so the fix is to let the paint happen before the rest of the work runs. Do only what the visible update depends on, update the DOM, then await scheduler.yield() — a browser primitive that ends the current task and queues the continuation as a new one. scheduler.yield is the right tool because it continues soon and in order, without the timers that other code can jump ahead of:
// fallback for browsers without scheduler.yield:
const yieldToPaint = () => (globalThis.scheduler?.yield
? globalThis.scheduler.yield()
: new Promise((r) => setTimeout(r, 0)));
save.addEventListener('click', async () => {
blockFor(35); // only what the update depends on
status.textContent = 'Saved'; // the visible update first
await yieldToPaint(); // hand the thread back: paint happens
blockFor(280); // analytics, storage, the rest
});click duration 40 ms
long task at 1140 ms, for 280 msSame work, same machine: the click now reports 40 ms — a good interaction — and the 280 ms remainder shows up afterwards as its own long task that no interaction waits for. Note what yielding does not do: it does not make the work cheaper or move it off the main thread, and the total busy time is unchanged. It only decides when the paint is allowed to happen. For genuinely parallel work there are web workers; for cheap updates, yielding is enough.
04. Step 3: when the framework re-renders too much
In a component framework the handler is often innocent and the render is the long task. A test catalogue rendered 4,000 rows in React 19 and filtered them on every keystroke, with CPU throttled 4x to imitate a mid-range phone. The plain version re-rendered every row on each character — the Profiler in React DevTools shows exactly this, every row lighting up with unchanged props — and the web-vitals INP beacon on the page read 248–328 ms (needs improvement) with 9–10 long tasks per word typed.
Two changes target it, and they compose. memo lets a row skip re-rendering when its props are equal — which holds here, because filtering returns the same row objects. useDeferredValue keeps the input on the fast path and lets React schedule the big list update after the keystroke has painted:
import { memo, useDeferredValue, useMemo, useState } from 'react';
const MemoRow = memo(Row); // same props -> same rendered row, skipped
function FastRows({ rows }: { rows: Array<{ id: string; name: string }> }) {
return rows.map((r) => <MemoRow key={r.id} item={r} />);
}
export function Catalogue({ data }: { data: Array<{ id: string; name: string }> }) {
const [query, setQuery] = useState('');
const deferred = useDeferredValue(query);
const rows = useMemo(
() => data.filter((r) => r.name.includes(deferred)),
[data, deferred],
);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<FastRows rows={rows} />
</div>
);
}plain: INP 248-328 ms (needs-improvement), 9-10 long tasks
fixed: INP 80-96 ms (good), 3-4 long tasksThe long tasks did not vanish — the list still renders, just later — but they no longer sit between the keystroke and the paint, which is what INP measures. Stability of props is the part teams get wrong: memo cannot help if the parent hands each row a fresh callback or object every render, so keep callbacks stable or let the React Compiler apply the same transformations automatically. The lists lesson covers the render model; useDeferredValue and memo are documented in full in the React docs.
05. Common mistakes
06. Check your understanding
07. Apply it
Take the slowest interaction on a page you own — the field beacon from the first lesson names it with its sub-parts:
- Record the interaction in the Performance panel and read the input delay, processing time and presentation delay for it.
- If processing dominates: reorder the handler so the visible update comes first,
scheduler.yield()(with the timer fallback), and confirm the event duration drops. - If presentation dominates: look for large DOM writes and layouts; batch writes, or move the heavy update behind
useDeferredValue. - In a React app, open the Profiler while interacting and check which components re-render with unchanged props; memoise those with stable props.
- Re-deploy and compare the field p75, not just the lab run.
08. Review prompt
Without looking back: what does an Event Timing duration measure, and which two observers describe an interaction? Name the three INP sub-parts and one cause for each. What does scheduler.yield() change about task boundaries, and why is a microtask not a substitute? What do memo and useDeferredValue each contribute to a slow filtered list, and which one fails when props change identity every render?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.