Loading...
Please waitLoading...
Please waitSchedule low-priority work through requestIdleCallback with a small React wrapper that exposes pending state, timeout awareness, and cancellation.
pnpm dlx uselab@latest add use-idle-callback
import { useIdleCallback } from "@/hooks/use-idle-callback"
export function WarmCacheButton() {
const { isPending, start, cancel } = useIdleCallback(
(deadline) => {
console.log("Time budget:", deadline.timeRemaining())
},
{ autoStart: false, timeout: 500 }
)
return (
<div className="space-y-2">
<button onClick={start} disabled={isPending}>
Schedule warm-up
</button>
<button onClick={cancel}>Cancel</button>
</div>
)
}useIdleCallback(callback, options?)| Name | Type | Description | Optional |
|---|---|---|---|
callback | (deadline: IdleDeadlineLike) => void | Runs when the browser grants idle time. | No |
options | UseIdleCallbackOptions | Controls automatic scheduling and timeout behavior. | Yes |
The hook returns an object { isSupported, isPending, didTimeout, start, cancel }:
| Name | Type | Description |
|---|---|---|
isSupported | boolean | Whether requestIdleCallback is available. |
isPending | boolean | Whether an idle callback is currently scheduled. |
didTimeout | boolean | Whether the last callback ran because the timeout elapsed rather than because the browser was idle. |
start | () => boolean | Schedules the idle callback and returns whether scheduling succeeded. |
cancel | () => void | Cancels any pending idle callback. |
interface UseIdleCallbackOptions {
timeout?: number
autoStart?: boolean
}timeout: Maximum wait time before the browser must run the callback.autoStart: Whether the hook should schedule immediately on mount. Defaults to true.Runs
0
Last budget
Not run yet
Timeout path
Idle budget
Good for analytics flushes, low-priority precomputation, and background hydration helpers that should stay out of the critical path.