Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created March 3, 2026 17:51
Show Gist options
  • Select an option

  • Save devhammed/d5b5986a08bda8f2486511fed14e6862 to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/d5b5986a08bda8f2486511fed14e6862 to your computer and use it in GitHub Desktop.
React Use Animation Frame Hook
import { DependencyList, useCallback, useEffect, useRef } from 'react';
const raf =
typeof window !== 'undefined'
? window.requestAnimationFrame ||
((cb: FrameRequestCallback) => window.setTimeout(() => cb(Date.now()), 1_000 / 60))
: () => undefined;
const caf = typeof window !== 'undefined' ? window.cancelAnimationFrame || window.clearTimeout : () => undefined;
export function useAnimationFrame(callback: FrameRequestCallback, deps: DependencyList = []) {
const requestRef = useRef<number | undefined>(undefined);
const previousTimeRef = useRef<number | undefined>(undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
const callbackFunction = useCallback(callback, deps);
const animate = useCallback(
(time: number) => {
if (previousTimeRef.current !== undefined) {
const deltaTime = time - previousTimeRef.current;
callbackFunction(deltaTime);
}
previousTimeRef.current = time;
requestRef.current = raf(animate);
},
[callbackFunction],
);
useEffect(() => {
requestRef.current = raf(animate);
return () => {
if (requestRef.current !== undefined) {
caf(requestRef.current);
}
};
}, [animate]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment