In this tutorial, we will learn to know Canvas Animation inside React Components with Request Animation Frame. Simple steps to start an animation inside a functional React component, and make sure it’s performant and cleans up after itself.
The relevant source code for this article can be found on GitLab 🙂
If you’re familiar with the HTML canvas element you know it’s relatively easy to create animations. We add a canvas element to our DOM and call a render function recursively with the help of requestAnimationFrame. The render function manipulates the context of the canvas and can add shapes, images, text, etc.
const ctx = canvas.getContext('2d');
Depending on which browser you use and how heavy your render function is, it executes around 60 times per second.
But what if you want to animate like this inside a React component?
This introduces some challenges. We certainly don’t want to rerender our React component 60 times per second. Let’s have a look at a solution.
We will create a single (functional) React component that uses three useRef hooks to help us achieve our goal.
Let’s start with the basics: