JAVASCRIPT

Implement useAnimationFrame for Smooth Animations

Create a custom React hook, `useAnimationFrame`, to execute functions on each browser animation frame, enabling smooth, performant, and synchronized animations.

import { useRef, useEffect, useCallback } from 'react';

function useAnimationFrame(callback) {
  const requestRef = useRef();
  const previousTimeRef = useRef();

  const animate = useCallback((time) => {
    if (previousTimeRef.current !== undefined) {
      const deltaTime = time - previousTimeRef.current;
      callback(deltaTime); // Execute the callback with delta time
    }
    previousTimeRef.current = time;
    requestRef.current = requestAnimationFrame(animate);
  }, [callback]);

  useEffect(() => {
    requestRef.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(requestRef.current);
  }, [animate]);
}

export default useAnimationFrame;
How it works: The `useAnimationFrame` hook provides an efficient way to run animations in React. It leverages the browser's `requestAnimationFrame` API, which schedules updates to occur before the browser's next repaint, leading to smoother animations. The hook takes a callback function that receives `deltaTime` (time elapsed since the last frame), allowing for frame-rate independent animations. `useRef` is used to store the animation frame ID and previous timestamp for accurate delta time calculation, while `useEffect` handles starting and cleaning up the animation loop.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs