Created
November 25, 2020 20:14
-
-
Save Problematic/8623e3a8f46228acb4a9d90e829ed0cc to your computer and use it in GitHub Desktop.
React useAnimationFrame hook
This file contains 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 { useRef, useEffect, useCallback } from 'react' | |
const useAnimationFrame = ( | |
tick: (dt: number, elapsed: number, frame: number) => void | |
) => { | |
const tickRef = useRef(tick) | |
const requestRef = useRef(0) | |
const prevTimeRef = useRef(0) | |
const elapsedRef = useRef(0) | |
const frameRef = useRef(0) | |
const animate = useCallback((time: number) => { | |
requestRef.current = requestAnimationFrame(animate) | |
if (prevTimeRef.current !== 0) { | |
const dt = (time - prevTimeRef.current) / 1000 | |
elapsedRef.current += dt | |
tickRef.current(dt, elapsedRef.current, ++frameRef.current) | |
} | |
prevTimeRef.current = time | |
}, []) | |
useEffect(() => { | |
tickRef.current = tick | |
}, [tick]) | |
useEffect(() => { | |
requestRef.current = requestAnimationFrame(animate) | |
return () => cancelAnimationFrame(requestRef.current) | |
}, [animate]) | |
} | |
export default useAnimationFrame |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment