Interaction to Next Paint (INP): finding and fixing slow clicks and taps
How to find what makes a page slow to respond to clicks and taps, using field data and Long Animation Frames, and the code changes that bring INP under 200 milliseconds.
- Topic
- Engineering
- Published
- Updated
- Reading time
- 7 min read
A user clicks an "Add to Cart" button or opens a navigation menu on a mobile device, and for 450 milliseconds, nothing happens. The interface feels rigid, unresponsive, and sluggish. The user taps again, inadvertently triggering multiple duplicate state updates, redundant API requests, or navigating away in frustration.
For years, frontend teams obsessed over First Input Delay (FID). But FID was a misleading metric: it only captured the initial latency before the browser began executing the first event handler, completely ignoring the duration of the JavaScript execution itself and the subsequent rendering pipeline. In March 2024, Google officially replaced FID with Interaction to Next Paint (INP) as a Core Web Vital. Unlike FID, INP measures the full end-to-end responsiveness of every single user click, tap, and keypress across the entire lifecycle of a session, reporting the worst interaction (at the 75th percentile).
Achieving a "Good" INP score (≤ 200 milliseconds) on real devices, with slow phone processors, busy networks and large component trees, is not solved with generic caching or a CDN. It requires a rigorous, architecture-first understanding of the browser's main-thread task queue, rendering pipeline, and modern scheduling primitives.
Why Standard Frameworks and Hydration Traps Destroy INP
Many development teams assume that adopting a modern React, Vue, or Next.js stack guarantees high performance. In production, client-side hydration patterns often become the primary destroyer of real-user responsiveness.
When a server-rendered or statically exported page lands on a low-to-mid-tier smartphone, the HTML appears quickly, so the page looks ready before it is. Behind the scenes, the browser must parse, compile, and execute several hundred kilobytes of JavaScript to attach event listeners and reconstruct the virtual DOM. If a user interacts with an input during this hydration phase, their event handler is queued behind a monolithic long task (tasks exceeding 50ms). The input sits completely blocked, easily accumulating 300ms to 800ms of input delay.
Beyond hydration, three pervasive application-level patterns routinely degrade INP:
- Synchronous State Cascades: Updating a top-level context or state store on every keystroke, forcing deep virtual DOM reconciliations across hundreds of unrelated child components before yielding back to the compositor.
- Layout Thrashing in Event Handlers: Interleaving DOM reads (e.g.,
element.getBoundingClientRect(),element.offsetHeight) with DOM writes (e.g., adding classes or inline styles), forcing the browser to compute synchronous style recalculations and reflows mid-handler. - Overloaded Event Telemetry: Dispatching unthrottled analytics pings, heat-mapping snapshots, or DOM-walking trackers synchronously inside click and scroll handlers.
The Anatomy of Interaction Latency: The Three Phases of INP
To systematically optimize INP, engineering teams must dissect every interaction into its three constituent phases: Input Delay, Processing Duration, and Presentation Delay.
1. Input Delay (Queue Latency): The elapsed time between when the physical hardware registers a gesture (pointerdown or keydown) and when the corresponding JavaScript callback actually begins execution. This delay is almost always caused by unrelated background tasks running on the main thread, such as heavy third-party scripts, unchunked hydration, or recurring timers.
2. Processing Duration: The cumulative execution time of all synchronous JavaScript event listeners bound to that user interaction (e.g., pointerdown, pointerup, and click). If your handler sorts an array of 5,000 items, evaluates heavy regular expressions, or reconciles an intricate component tree synchronously, processing duration explodes.
3. Presentation Delay: The time required by the browser after event handlers finish to calculate style changes, perform layout reflows, paint pixels into bitmaps, and composite layers onto the display. Heavy DOM depth (exceeding 1,500 nodes), complex CSS selectors, and forced layout invalidations turn presentation delay into a major hidden bottleneck.
Four Concrete Architectural Strategies for Sub-200ms Interactions
Fixing poor INP requires architectural discipline rather than cosmetic micro-optimizations. Here are four approaches that work well:
Strategy 1: Cooperative Main-Thread Scheduling with scheduler.yield()
When an interaction triggers multiple sequential operations (e.g., validating input, updating UI feedback, and processing data), never run them inside a single monolithic synchronous block. Use cooperative scheduling to yield control back to the browser compositor, allowing the next frame to render immediately:
async function handleSearchFilter(query) {
// 1. Immediate visual feedback: show loading spinner or highlight
setLoadingState(true);
// Yield execution to allow the browser to paint the visual feedback
if ('scheduler' in window && 'yield' in window.scheduler) {
await window.scheduler.yield();
} else {
await new Promise(resolve => setTimeout(resolve, 0));
}
// 2. Heavy computational work: filtering or complex calculation
const results = filterDataset(query);
updateSearchResults(results);
setLoadingState(false);
}
Strategy 2: Observability with the Long Animation Frames (LoAF) API
Chrome 123+ introduced the Long Animation Frames (LoAF) API, which completely replaces the blunt Long Tasks API by identifying the exact script source, character position, and invoker function responsible for rendering delays:
const loafObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 50) {
console.warn('[LoAF Bottleneck Detected]', {
duration: entry.duration,
blockingDuration: entry.blockingDuration,
renderStart: entry.renderStart,
scripts: entry.scripts.map(s => ({
invoker: s.invoker,
sourceURL: s.sourceURL,
sourceCharPosition: s.sourceCharPosition,
executionDuration: s.executionDuration
}))
});
}
}
});
loafObserver.observe({ type: 'long-animation-frame', buffered: true });
Strategy 3: Non-Blocking Telemetry with navigator.sendBeacon()
Never perform synchronous network dispatches or state serialization while handling a user interaction. Replace synchronous fetch or XHR telemetry calls with navigator.sendBeacon() or fetch(url, { keepalive: true }), which hand off the payload directly to the browser's network daemon without pausing main-thread rendering.
Strategy 4: Flatten DOM Depth and Optimize CSS Paint Containment
Presentation delay spikes when style recalculation must evaluate deeply nested DOM trees. Apply CSS contain: layout style paint; or content-visibility: auto; to off-screen or dynamic panels (such as complex dropdown menus or modal overlays). This isolates layout reflows strictly to the target subtree rather than invalidating the entire page layout.
Practical Decision Matrix and Production Audit Checklist
Before deploying updates to production, use this structured decision matrix to triage performance bottlenecks:
Interaction Phase Primary Symptom Root Cause Fix Input Delay Interaction lag > 100ms before handler runs Long tasks, hydration lock-in, unconstrained third-party scripts Defer non-critical bundles, split bundles with dynamicimport(), adopt islands or partial hydration
Processing Duration
Handler script execution > 50ms
Synchronous data sorting, massive state cascades, heavy DOM reconciliation
Chunk tasks via scheduler.yield(), offload heavy computations to Web Workers
Presentation Delay
Visual update delayed after handler completion
Excessive DOM depth, forced synchronous layouts, uncontained CSS recalculations
Apply content-visibility: auto, eliminate layout reads after writes, flatten DOM hierarchies
Production INP Audit Checklist:
- [x] Audit RUM percentiles: Ensure your Real User Monitoring (RUM) tracks INP at the 75th percentile segmented by device tier (specifically mobile vs. desktop).
- [x] Check for layout thrashing: Ensure no
window.getComputedStyle(),offsetWidth, orscrollTopqueries are executed after DOM mutations in the same microtask. - [x] Enforce cooperative yielding: Wrap any loop or computation processing over 50 items in a yielding loop structure.
- [x] Throttle high-frequency input: Ensure search inputs, slider drags, and resize handlers are debounced or throttled using
requestAnimationFrame. - [x] Isolate third-party scripts: Run tag managers, chat widgets, and social embeds inside sandboxed Web Workers using Partytown or load them strictly on user idle.
Trade-offs and next steps
Engineering for high responsiveness requires acknowledging fundamental software trade-offs. Splitting every synchronous task with scheduler.yield() introduces small microtask overhead. If overused on trivial 2ms handlers, excessive yielding can marginally increase cumulative CPU cycles. The objective is not to yield on every single line of code, but to protect the 50ms task threshold.
Similarly, offloading data processing to Web Workers eliminates main-thread contention, but introduces structured-clone serialization costs over postMessage. For datasets smaller than a few kilobytes, the serialization overhead may exceed the computation time. Measure before isolating.
Next Steps: Begin by collecting field data using the web-vitals JavaScript library or your existing observability provider. Filter your worst-performing interactions by INP duration and URL pathname. In 80% of production applications, fixing the top two slowest event handlers (typically search filters, navigation drawers, or multi-step checkout forms) is sufficient to bring your entire site into Google's green zone (≤ 200ms), safeguarding both user conversion rates and organic search visibility.
Written by Lay Shah, an independent developer building websites and tools for small businesses. Discuss a brief More articles