-
Notifications
You must be signed in to change notification settings - Fork 22
/
useAnimationFrame.ts
44 lines (36 loc) · 1.24 KB
/
useAnimationFrame.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { useEffect, useRef, useState } from 'react'
// Calls a callback with the milliseconds elapsed since the first frame. Returns
// a function to start and stop the animation.
export const useAnimationFrame = (callback: FrameRequestCallback) => {
const [animating, setAnimating] = useState(false)
const requestRef = useRef<number>()
const startTimestampMsRef = useRef<number>()
const callbackRef = useRef<FrameRequestCallback>(callback)
callbackRef.current = callback
const animate: FrameRequestCallback = (timestampMs) => {
if (startTimestampMsRef.current === undefined) {
startTimestampMsRef.current = timestampMs
}
callbackRef.current(timestampMs - startTimestampMsRef.current!)
requestRef.current = requestAnimationFrame(animate)
}
useEffect(() => {
if (!animating) {
requestRef.current = undefined
startTimestampMsRef.current = undefined
return
}
requestRef.current = requestAnimationFrame(animate)
// Cancel on cleanup.
return () => {
if (requestRef.current !== undefined) {
cancelAnimationFrame(requestRef.current)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [animating])
return {
animating,
setAnimating,
}
}