Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/artelydev/use-listen-on-animation-frame

Better alternative to setInterval for frequent changes in your UI
https://github.com/artelydev/use-listen-on-animation-frame

animation animation-frame interval react react-hook use-animation-frame

Last synced: 5 days ago
JSON representation

Better alternative to setInterval for frequent changes in your UI

Awesome Lists containing this project

README

        

useListenOnAnimationFrame


Invoke & track your functions on every animation frame



ESM
· CommonJS
· 1 dependency



Github Actions Build Status


npm version


license: MIT


npm bundle size
typed

Navigation

- [Quick start](#quick-start)
- [Docs (website)](https://artelydev.github.io/use-listen-on-animation-frame/)
- [Usage](./docs/usage.md)
- [Why this package](./docs/comparison.md)
- [API](./docs/api.md)
- [Advanced usage](./docs/advanced-usage.md)
- [Q&A](./docs/qa.md)

## Quick start

### Installation

```bash
$ npm i use-listen-on-animation-frame
```

### Use

Library provides 2 hooks which are `useAnimationFrame`, `useListenOnAnimationFrame`. See [Usage](./docs/usage.md), [API](./docs/api.md) and [Advanced usage](./docs/advanced-usage.md) for more.

#### Basic

Run function on every animation frame

```tsx
import React, { useCallback, useState } from "react";
import { useAnimationFrame } from "use-listen-on-animation-frame";

const Component = () => {
const [date, setDate] = useState(new Date());

const syncDate = useCallback(() => {
setDate(new Date());
}, []);

useAnimationFrame(syncDate);

return

{date}
;
};
```

#### Multiple side effects

Run function once on every animation frame, and apply multiple listeners to it. Stop and start function & listeners when you want.

```tsx
import React, { useState } from "react";
import { useListenOnAnimationFrame } from "use-listen-on-animation-frame";

const getCostlyRandomNumber = () => {
const random = Math.random() * 300;

let counter = 0;

for (; counter < random; counter++) {
counter++;
}

return counter;
};

const Component = () => {
const [number, setNumber] = useState(0);

const [addListener, _removeListener, stop, start] = useListenOnAnimationFrame(
getCostlyRandomNumber,
{ autoStart: false } // optional
);

useEffect(() => {
addListener((thisFrameRandom, _previousFrameRandom) => {
setNumber(thisFrameRandom);
});

addListener((thisFrameRandom) => {
// do something;
});

addListener((thisFrameRandom) => {
for (let i = 0; i < thisFrameRandom; i++) {
// do something
}
});
}, [addListener]);

useEffect(() => {
if (somethingBadHappened) {
stop();
}
}, [stop, somethingBadHappened]);

useEffect(() => {
if (somethingGoodHappened) {
start();
}
}, [start, somethingGoodHappened]);

return (


{number}


);
};
```