Hard
React Custom Animation Hook: Fixing Performance Issues with requestAnimationFrame
You're building a data visualization component that needs to smoothly animate between states. What's wrong with this implementation of a custom animation hook?
1function useAnimatedValue(targetValue, duration = 500) {2 const [currentValue, setCurrentValue] = useState(targetValue);3 const startTimeRef = useRef(null);4 const animationFrameId = useRef(null);56 const animate = useCallback((timestamp) => {7 if (!startTimeRef.current) {8 startTimeRef.current = timestamp;9 }1011 const elapsed = timestamp - startTimeRef.current;12 const progress = Math.min(elapsed / duration, 1);1314 const newValue = currentValue + (targetValue - currentValue) * progress;15 setCurrentValue(newValue);1617 if (progress < 1) {18 animationFrameId.current = requestAnimationFrame(animate);19 }20 }, [currentValue, targetValue, duration]);2122 useEffect(() => {23 animationFrameId.current = requestAnimationFrame(animate);24 return () => {25 if (animationFrameId.current) {26 cancelAnimationFrame(animationFrameId.current);27 }28 };29 }, [targetValue]);3031 return currentValue;32}