useDeferredInteraction returns true after the first user action on the page or after a timeout. Load chats, analytics and maps behind it, and they stay out of the page load window that Lighthouse and Core Web Vitals measure.
Preview
If you have already scrolled, the flag is on. Press Reset and the chat waits for your next scroll, key press or tap.
Waiting for the first interaction
Scroll, press a key or tap anywhere. Without that, the widget loads after 15 seconds.
Same flag, another component: false
Installation
Usage
import { useDeferredInteraction } from "@/hooks/use-deferred-interaction"
export function SupportChat() {
const ready = useDeferredInteraction()
useEffect(() => {
if (!ready) return
const script = document.createElement("script")
script.src = "https://chat.example.com/widget.js"
script.async = true
document.body.append(script)
}, [ready])
return null
}Examples
Interaction only
Pass null to drop the fallback timer. Synthetic test runs never scroll or click, so the script will not load during the audit at all.
const ready = useDeferredInteraction(null)Several widgets, one flag
The interaction is shared: the first scroll turns the flag on for every component on the page. Each call keeps its own timeout.
function Analytics() {
const ready = useDeferredInteraction(3000)
return ready ? <AnalyticsScript /> : null
}
function MapBlock() {
// waits longer, but still switches on with the first scroll
const ready = useDeferredInteraction(10_000)
return ready ? <InteractiveMap /> : <MapPreviewImage />
}With next/script
In Next.js render the Script component behind the flag.
const ready = useDeferredInteraction()
return ready ? (
<Script src="https://widget.example.com/embed.js" strategy="afterInteractive" />
) : nullParameters
| Name | Type | Default | Description |
|---|---|---|---|
| timeout | number | null | 5000 | Milliseconds after mount when the flag turns on anyway. null waits for an interaction only |
Returns
| Name | Type | Description |
|---|---|---|
| ready | boolean | true after the first scroll, pointerdown, keydown or touchstart on the page, or after the timeout |
| resetDeferredInteraction() | () => void | Separate export that forgets the interaction. For tests and demos |
Features
- Shared state. One set of listeners for the whole page, removed right after the first interaction
- Remembers across navigation. After client-side navigation the flag stays on, widgets do not wait again
- Hydration-safe. Built on useSyncExternalStore and returns false on the server