fix leaky ref

This commit is contained in:
Steve Ruiz 2021-12-22 00:40:37 +00:00
parent 4da632d5d8
commit e8befe2290

View file

@ -20,10 +20,11 @@ export function useCursorAnimation(ref: any, point: number[]) {
const rTimestamp = React.useRef(performance.now())
const rLastRequestId = React.useRef<any>(0)
const rTimeoutId = React.useRef<any>(0)
const rSpline = React.useRef(new Spline())
const [spline] = React.useState(() => new Spline())
// Animate an animation
const animateNext = React.useCallback((animation: Animation) => {
const animateNext = React.useCallback(
(animation: Animation) => {
const start = performance.now()
function loop() {
const t = (performance.now() - start) / animation.duration
@ -31,7 +32,7 @@ export function useCursorAnimation(ref: any, point: number[]) {
const elm = ref.current
if (!elm) return
const point = animation.curve
? rSpline.current.getSplinePoint(t + animation.start)
? spline.getSplinePoint(t + animation.start)
: Vec.lrp(animation.from, animation.to, t)
elm.style.setProperty('transform', `translate(${point[0]}px, ${point[1]}px)`)
rLastRequestId.current = requestAnimationFrame(loop)
@ -49,12 +50,13 @@ export function useCursorAnimation(ref: any, point: number[]) {
}
}
loop()
}, [])
},
[spline]
)
// When the point changes, add a new animation
React.useLayoutEffect(() => {
const now = performance.now()
const spline = rSpline.current
if (rState.current === 'stopped') {
rTimestamp.current = now
rPrevPoint.current = point
@ -92,7 +94,7 @@ export function useCursorAnimation(ref: any, point: number[]) {
return () => {
clearTimeout(rTimeoutId.current)
}
}, [point])
}, [point, spline])
}
class Spline {