Created
March 3, 2026 17:51
-
-
Save devhammed/d5b5986a08bda8f2486511fed14e6862 to your computer and use it in GitHub Desktop.
React Use Animation Frame Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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