# useAnimationFrame

Calls `callback` on every animation frame while `active`, with the time since the previous frame. Always calls the latest `callback`, so it can read current props without restarting the loop. Cancelled on unmount and when `active` turns false. Browsers pause it in background tabs.

The callback runs outside React rendering: write to a ref, a canvas, or a style directly. Calling `setState` every frame re-renders 60+ times a second.

## Import

```ts
import { useAnimationFrame } from '@vincent.ri/react-tils'
// or only this hook
import { useAnimationFrame } from '@vincent.ri/react-tils/useAnimationFrame'
```

## Usage

```ts
const canvas = useRef<HTMLCanvasElement>(null)
const x = useRef(0)
useAnimationFrame((deltaMs) => {
  x.current = (x.current + deltaMs * 0.1) % 300
  const ctx = canvas.current?.getContext('2d')
  ctx?.clearRect(0, 0, 300, 50)
  ctx?.fillRect(x.current, 10, 30, 30)
}, playing)
```

## When to use it

Drawing on a canvas, a game loop, physics, or smoothing a value that follows the pointer.

## When not to

CSS transitions, CSS animations, or the Web Animations API (`element.animate()`) can do it; they can run off the main thread. For work every second or slower, use `useInterval`.

## API

```ts
function useAnimationFrame(callback: (deltaMs: number, timeMs: number) => void, active?: boolean): void
```

| Parameter | Description |
| --- | --- |
| `callback` | Called each frame with `deltaMs` (0 on the first frame) and the frame timestamp `timeMs`. Can change every render. |
| `active` | Run while `true`. Default `true`. |

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useRafLoop`.

---

173 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useAnimationFrame.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useAnimationFrame/
Previous: [useThrottledCallback](https://vincentri.github.io/react-tils/hooks/useThrottledCallback.md)
Next: [useCopyToClipboard](https://vincentri.github.io/react-tils/hooks/useCopyToClipboard.md)
