useAnimationFrame()

A React hook for working with animation frames

This hook let you work with animation frames in React components using a simple request/cancel api. I use it whenever I do JS animations (animations that are too complex to be done with pure CSS).

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

export const useAnimationFrame = () => {
    const id = useRef(0);

    // Cancel any pending requests when unmounting
    useEffect(() => () => {
        cancelAnimationFrame(id.current);
    }, []);

    const cancel = useCallback(() => {
        cancelAnimationFrame(id.current);
    }, []);

    const request = useCallback(cb => {
        cancelAnimationFrame(id.current);
        id.current = requestAnimationFrame(cb);
        return id.current; // For manual cancellation
    }, []);

    return { request, cancel };
};

You can use it like so:

js
const { request, cancel } = useAnimationFrame();

request(() => {/* Do something in the next repaint */});
cancel(); // Cancel the currently pending request
Share this lovely stuff with your besties!

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.