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
@templateT Type of arguments passed to the requestAnimationFrame callback function.
Props for the useRaf.
| Property | Type | Required | Description |
|---|---|---|---|
cb | (timeElapsed: number, repeat: () => void, ...args: T) => void | ✓ | Callback invoked on each animation frame. |
UseRafResult
Result object returned by useRaf.
| Index | Type | Description |
|---|---|---|
[0] | (...args: T) => void | start - function to invoke requestAnimationFrame. |
[1] | () => void | cancel — function to invoke cancelAnimationFrame. |
