Skip to content

Instantly share code, notes, and snippets.

@Wigny
Created September 18, 2025 15:40
Show Gist options
  • Select an option

  • Save Wigny/721934b31a4fcdd0a5bd8c7c4037f7d4 to your computer and use it in GitHub Desktop.

Select an option

Save Wigny/721934b31a4fcdd0a5bd8c7c4037f7d4 to your computer and use it in GitHub Desktop.
import { useLayoutEffect } from 'react';
import { duration } from 'dayjs';
import { type Duration } from 'dayjs/plugin/duration';
export function useAnimationFrame(callback: (deltaTime: Duration) => void): void {
useLayoutEffect(() => {
let requestID: number;
let previousTime = 0;
const tick = (time: number) => {
const deltaTime = duration(time - previousTime, 'milliseconds');
callback(deltaTime);
previousTime = time;
requestID = requestAnimationFrame(tick);
};
requestID = requestAnimationFrame(tick);
return () => cancelAnimationFrame(requestID);
}, [callback]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment