Skip to content

useIdleCallback

Hook to invoke a callback when the browser is idle.

See: requestIdleCallback in React. The options parameter differs from IdleRequestOptions type: it adds the possibility to pass another property unsupportedBehavior to specify what do if requestIdleCallback is not supported.

Demo

INFO

The component has:

  • a iterations variable of type string.
  • a log variable of type string.
  • a function invoke returned from useIdleCallback hook, initialized with a cb that update log variable with message "RequestIdleCallback executed".
  • a button start that when clicked executes start function that executes invoke function and updates iterations variable inside a loop with iteration index.
Loading demo…
Show source code
tsx
import { useState } from "react"
import { useIdleCallback } from "../../../..";


export const UseIdleCallback = () => {
	const [iterations, setIterations] = useState(0);
	const [log, setLog] = useState("");
	const [isSupported, invoke] = useIdleCallback(() => setLog("RequestIdleCallback executed"));

	const start = async() => {
		invoke();
		for (let i = 0; i < 5_000; i++) {
			setTimeout(() => setIterations(i + 1), 5);
		}
	}
	const reset = () => {
		setLog("");
		setIterations(0);
	}
	return (<div>
		<p>Supported: {isSupported ? "Yes" : "No"}</p>
		<p>Iterations are: {iterations}</p>
		<p>Log is: {log}</p>
		<button onClick={start}>START</button>
		<button onClick={reset}>RESET</button>
	</div>);
}

Types

UseIdleCallbackProps

Props accepted by useIdleCallback

PropertyTypeRequiredDescription
cbIdleRequestCallbackCallback passed to requestIdleCallback, invoked during browser idle periods.
optsIdleRequestOptionsOptions forwarded to requestIdleCallback (e.g. { timeout: 2000 }).

UseIdleCallbackResult

Result tuple returned by useIdleCallback.

IndexTypeDescription
[0]booleanlocation - possible states of the Geolocation API: supported (with an optional position) or not supported.
[1]() => voidinvoke - function to invoke execution.
[2]() => voidcancel - function to cancel execution.

Released under the MIT License.