Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/franciscop/use-animation-frame

A React hook to run requestAnimationFrame seamlessly
https://github.com/franciscop/use-animation-frame

Last synced: 13 days ago
JSON representation

A React hook to run requestAnimationFrame seamlessly

Awesome Lists containing this project

README

        

# use-animation-frame

A hook to effortlessly run [`requestAnimationFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) in React ([**demo**](https://codesandbox.io/s/fps-counter-8jfdg)):

```js
import useAnimationFrame from 'use-animation-frame';

const Counter = () => {
const [time, setTime] = useState(0);
useAnimationFrame(e => setTime(e.time));
return

Running for:
{time.toFixed(1)}s
;
};
```

Inspired by [CSS-Tricks' Using requestAnimationFrame with React Hooks](https://css-tricks.com/using-requestanimationframe-with-react-hooks/) and my [twitter reply](https://mobile.twitter.com/FPresencia/status/1164193851931631616).

## API

Accepts a function that will be called on each requestAnimationFrame step. If there's a re-render and a new function is created, it'll use that instead of the previous one:

```js
useAnimationFrame(callback);
```

The callback receives a single parameter, which is an object with two properties (based on [the `performance.now()` API](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now)):

- `time`: the absolute time _since the hook was first mounted_. This is useful for wall clock, general time, etc.
- `delta`: the time _since the hook was run last_. This is useful to measure e.g. FPS.

All times are in the International System of Units **seconds**, including decimals.

## Example: FPS counter

With my other library [use-interpolation](https://www.npmjs.com/package/use-interpolation) it's easy to calculate the FPS ([see in CodeSandbox](https://codesandbox.io/s/angry-voice-8jfdg)):

```js
import React, { useState } from "react";
import useInterpolation from 'use-interpolation';
import useAnimationFrame from 'use-animation-frame';

const Counter = () => {
const [time, setTime] = useState(0);
// 1s of interpolation time
const [fps, setFps] = useInterpolation(1000);
useAnimationFrame(e => {
setFps(1 / e.delta);
setTime(e.time);
});
return (


{time.toFixed(1)}s


{fps && Math.floor(fps.value)} FPS

);
};
```