Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add useAnimationLoop hook #129

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
61 changes: 61 additions & 0 deletions src/hooks/useAnimationLoop/useAnimationLoop.stories.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Meta } from '@storybook/blocks';

<Meta title="hooks/useAnimationLoop" />

# useAnimationLoop

useAnimationLoop hook is a wrapper around requestAnimationFrame method. This hook will execute a
callback function every next frame.
AlenaAlyona marked this conversation as resolved.
Show resolved Hide resolved

## Reference

```ts
function useAnimationLoop(callback: (delta: number) => void, enabled = false): void;
```

### Parameters

- `callback` - function accepts `delta` parameter which represents time passed since last
invocation; - `callback` function will be called on every animation frame
AlenaAlyona marked this conversation as resolved.
Show resolved Hide resolved
- `enabled` - boolean which is used to play and pause the requestAnimationFrame

### Returns

- `void`

## Usage

```tsx
function DemoComponent(): ReactElement {
const [currentTimestamp, setCurrentTimestamp] = useState(Date.now);
const [state, toggle] = useToggle(true);
AlenaAlyona marked this conversation as resolved.
Show resolved Hide resolved
useAnimationLoop(() => {
setCurrentTimestamp(Date.now);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this example, it might be more useful to do something (e.g. log) the delta that is passed, to better showcase the features of this hook.

}, state);

return (
<div>
<div className="alert alert-primary">
<h4 className="alert-heading">Instructions!</h4>
<p className="mb-0">Click on the button to toggle the animation loop</p>
</div>
<div className="card border-dark" data-ref="test-area">
<div className="card-header">Test Area</div>
<div className="card-body">
<p>{currentTimestamp}</p>

<button
type="button"
// eslint-disable-next-line react/jsx-handler-names, react/jsx-no-bind
onClick={(): void => {
toggle();
}}
>
Toggle animation loop
</button>
</div>
</div>
</div>
);
}
```
48 changes: 48 additions & 0 deletions src/hooks/useAnimationLoop/useAnimationLoop.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* eslint-disable react/jsx-no-literals */
import type { StoryObj } from '@storybook/react';
import { useState, type ReactElement } from 'react';
import { useToggle } from '../useToggle/useToggle.js';
import { useAnimationLoop } from './useAnimationLoop.js';

export default {
title: 'hooks/useAnimationLoop',
};

function DemoComponent(): ReactElement {
const [currentTimestamp, setCurrentTimestamp] = useState(Date.now);
const [state, toggle] = useToggle(true);
useAnimationLoop(() => {
setCurrentTimestamp(Date.now);
}, state);

return (
<div>
<div className="alert alert-primary">
<h4 className="alert-heading">Instructions!</h4>
<p className="mb-0">Click on the button to toggle the animation loop</p>
</div>
<div className="card border-dark" data-ref="test-area">
<div className="card-header">Test Area</div>
<div className="card-body">
<p>{currentTimestamp}</p>

<button
type="button"
// eslint-disable-next-line react/jsx-handler-names, react/jsx-no-bind
onClick={(): void => {
toggle();
}}
>
Toggle animation loop
</button>
</div>
</div>
</div>
);
}

export const Demo: StoryObj = {
render() {
return <DemoComponent />;
},
};
10 changes: 10 additions & 0 deletions src/hooks/useAnimationLoop/useAnimationLoop.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { renderHook } from '@testing-library/react';
import { useAnimationLoop } from './useAnimationLoop.js';

describe('useAnimationLoop', () => {
leroykorterink marked this conversation as resolved.
Show resolved Hide resolved
it('should not crash', async () => {
renderHook(useAnimationLoop, {
initialProps: undefined,
});
});
});
41 changes: 41 additions & 0 deletions src/hooks/useAnimationLoop/useAnimationLoop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useCallback, useEffect, useRef } from 'react';
import { useRefValue } from '../useRefValue/useRefValue.js';

/**
* useAnimationLoop hook is a wrapper around requestAnimationFrame method.
* This hook will execute a callback function every next frame.
*
* @param callback - callback function with @param delta which represents time passed since last invocation
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This docs (still) say delta, while the implementation (has changed?) returns the actual time.

When running an individual animationFrame, the time might be useful. When you running them in a loop, the delta is often more useful.
I don't mind also forwarding the timestamp, but I feel we should at least calculate and pass the delta.

* @param enabled - boolean which is used to play and pause the requestAnimationFrame
*/
export function useAnimationLoop(callback: (delta: number) => void, enabled = false): void {
const animationFrameRef = useRef(0);
const lastTimeRef = useRef(0);
const callbackRef = useRefValue(callback);

const tick = useCallback((time: number): void => {
const delta = time - lastTimeRef.current;
lastTimeRef.current = time;

callbackRef.current?.(delta);

animationFrameRef.current = requestAnimationFrame(tick);
}, []);

const play = useCallback(() => {
lastTimeRef.current = performance.now();
requestAnimationFrame(tick);
}, [tick]);

const pause = useCallback(() => {
cancelAnimationFrame(animationFrameRef.current);
}, []);

useEffect(() => {
if (enabled) {
play();
}

return pause;
}, [enabled, pause, play]);
}