useCanvasAnimation()

A React hook for rendering canvas animations

This hook provides a simple API for rendering animations with <canvas/>. The hook takes a renderer function, that should return a function that will be called in a loop on each animation frame.

The renderer function will be called with a CanvasRenderingContext2D object, which you can use to draw on the canvas.

The reason for using a function that returns a function is to allow you to set up values that will be used across renders.

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

export const useCanvasAnimation = (renderer) => {
    const canvas = useRef();
    const frameId = useRef(0);

    useEffect(() => {
        const render = renderer();
        const update = () => {
            frameId.current = requestAnimationFrame(() => {
                render(canvas.current?.getContext('2d'));
                update();
            });
        };
        update();
        return () => cancelAnimationFrame(frameId.current);
    }, [renderer]);

    return canvas;
}

You can use it like so:

js
const Example = () => {
    const canvas = useCanvasAnimation(() => {
        // Use this part to initialze values to be used across renders

        return (ctx) => {
            // Render something using the context in ctx
        };
    });
    return (
        <canvas ref={canvas}/>
    )
}

In the example below, we use the useCanvasAnimation hook to create a simple animation that draws a circle that moves across the canvas. The renderer function is called on each animation frame, and it updates the position of the circle and redraws it.

Code Playground
Share this magical content with your crew!

A newsletter for front-end web developers

Stay up-to-date with my latest articles, experiments, tools, and much more!

Issued monthly (or so). No spam. Unsubscribe any time.