React useRequestAnimationFrame Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to use the useRequestAnimationFrame hook in React to animate a function, ensuring that it runs before every repaint. This hook is useful for creating smooth and efficient animations in web applications. We will walk through the process of creating the hook and implementing it in a simple counter component that updates in real-time.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38405{{"`React useRequestAnimationFrame Hook`"}} react/event_handling -.-> lab-38405{{"`React useRequestAnimationFrame Hook`"}} react/hooks -.-> lab-38405{{"`React useRequestAnimationFrame Hook`"}} react/use_state_reducer -.-> lab-38405{{"`React useRequestAnimationFrame Hook`"}} end

React useRequestAnimationFrame Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To run an animating function before every repaint, use the useRef() hook to create requestRef and previousTimeRef variables. Then, define an animate() function that updates these variables, runs the callback, and calls Window.requestAnimationFrame() perpetually. Lastly, use the useEffect() hook with an empty array to initialize the value of requestRef with Window.requestAnimationFrame(), and use the returned value and Window.cancelAnimationFrame() to clean up when the component unmounts.

Here is an example implementation of useRequestAnimationFrame():

const useRequestAnimationFrame = (callback) => {
  const requestRef = React.useRef();
  const previousTimeRef = React.useRef();

  const animate = (time) => {
    if (previousTimeRef.current) {
      callback(time - previousTimeRef.current);
    }
    previousTimeRef.current = time;
    requestRef.current = requestAnimationFrame(animate);
  };

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

To use this custom hook in a component, simply pass a callback function to it. For example, to create a simple counter that updates at 100 FPS:

const Counter = () => {
  const [count, setCount] = React.useState(0);

  useRequestAnimationFrame((deltaTime) => {
    setCount((prevCount) => (prevCount + deltaTime * 0.01) % 100);
  });

  return <p>{Math.round(count)}</p>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<Counter />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useRequestAnimationFrame Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like