From 767834b94eddb397ac75f1fb3d8fcab6908b0119 Mon Sep 17 00:00:00 2001 From: Matt Perry Date: Thu, 16 May 2024 14:52:43 +0200 Subject: [PATCH] Cleanup --- .../framer-motion/src/value/use-spring.ts | 55 +++++++++---------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/packages/framer-motion/src/value/use-spring.ts b/packages/framer-motion/src/value/use-spring.ts index c34c9ad401..395b35d6b3 100644 --- a/packages/framer-motion/src/value/use-spring.ts +++ b/packages/framer-motion/src/value/use-spring.ts @@ -39,6 +39,31 @@ export function useSpring( null ) const value = useMotionValue(isMotionValue(source) ? source.get() : source) + const latestValue = useRef(value.get()) + const latestSetter = useRef<(v: number) => void>(() => {}) + + const startAnimation = () => { + /** + * If the previous animation hasn't had the chance to even render a frame, render it now. + */ + const animation = activeSpringAnimation.current + + if (animation && animation.time === 0) { + animation.sample(frameData.delta) + } + + stopAnimation() + + activeSpringAnimation.current = animateValue({ + keyframes: [value.get(), latestValue.current], + velocity: value.getVelocity(), + type: "spring", + restDelta: 0.001, + restSpeed: 0.01, + ...config, + onUpdate: latestSetter.current, + }) + } const stopAnimation = () => { if (activeSpringAnimation.current) { @@ -47,32 +72,6 @@ export function useSpring( } useInsertionEffect(() => { - let latestValue: number - let latestSet: (v: number) => void - - const startAnimation = () => { - /** - * If the previous animation hasn't had the chance to even render a frame, render it now. - */ - const animation = activeSpringAnimation.current - - if (animation && animation.time === 0) { - animation.sample(frameData.delta) - } - - stopAnimation() - - activeSpringAnimation.current = animateValue({ - keyframes: [value.get(), latestValue], - velocity: value.getVelocity(), - type: "spring", - restDelta: 0.001, - restSpeed: 0.01, - ...config, - onUpdate: latestSet, - }) - } - return value.attach((v, set) => { /** * A more hollistic approach to this might be to use isStatic to fix VisualElement animations @@ -80,8 +79,8 @@ export function useSpring( */ if (isStatic) return set(v) - latestValue = v - latestSet = set + latestValue.current = v + latestSetter.current = set frame.update(startAnimation)