Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/franciscop/use-animation-frame
- Owner: franciscop
- License: mit
- Created: 2019-11-10T11:31:19.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2024-08-23T14:12:04.000Z (3 months ago)
- Last Synced: 2024-09-23T14:41:36.833Z (about 2 months ago)
- Language: JavaScript
- Size: 25.4 KB
- Stars: 22
- Watchers: 3
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- Funding: .github/FUNDING.yml
- License: LICENSE
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));
returnRunning 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
);
};
```