Skip to content

Instantly share code, notes, and snippets.

@Problematic
Created November 25, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Problematic/8623e3a8f46228acb4a9d90e829ed0cc to your computer and use it in GitHub Desktop.
Save Problematic/8623e3a8f46228acb4a9d90e829ed0cc to your computer and use it in GitHub Desktop.
React useAnimationFrame hook
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