Skip to content

useRaf

Hook to execute a callback function with requestAnimationFrame to optimize performance. Refer to (requestAnimationFrame)[https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame].

Demo

INFO

The component renders a textarea element and when it is resized, updates state variable inside function start returned from useRaf hook.

Loading demo…
Show source code
tsx
import { useState } from "react"
import { useRaf, useResizeObserver } from "../../../..";

export const UseRaf = () => {
	const [state, setState] = useState({ width: 0, height: 0 });
	const [start] = useRaf((_: number, __:()=>void, dim: DOMRectReadOnly) => {
		setState({ width: dim.width, height: dim.height });
	});
	const {ref} = useResizeObserver<HTMLTextAreaElement>(
		(entries: ResizeObserverEntry[]) => {
			start(entries[0].contentRect);
		},
		{ mode: "ref" }
	);

	return <div>
		<p>{"Textarea dimension: " + JSON.stringify(state)}</p>
		<textarea ref={ref} rows={3}></textarea>
	</div>
}

Types

UseRafProps

  • @template T Type of arguments passed to the requestAnimationFrame callback function.

Props for the useRaf.

PropertyTypeRequiredDescription
cb(timeElapsed: number, repeat: () => void, ...args: T) => voidCallback invoked on each animation frame.

UseRafResult

Result object returned by useRaf.

IndexTypeDescription
[0](...args: T) => voidstart - function to invoke requestAnimationFrame.
[1]() => voidcancel — function to invoke cancelAnimationFrame.

Released under the MIT License.