All guides

React · Canvas · Resource lifecycle

Canvas in React: animation without unnecessary renders or leaks

Author: Grundy · Checked: November 13, 2026

How can a canvas animation stay in sync with React controls without recalculating the algorithm or leaving callbacks running after removal? We will follow the site’s sorting player, sizing Hook, share-link restoration and video recorder. Dotted-underlined terms have definitions on hover, click or keyboard focus. Code excerpts use React 19.2.8 and AlgiViz 0.11.2.

1. A React render and a canvas frame

In SortingPlayer, setTime passes the current animation time to React on each loop callback. React uses it to calculate the interface during a and applies the result during a . The canvas picture is drawn separately through commands such as fillRect. The text description and slider need the same time as the picture, so these state updates serve a purpose. The remaining sections show how to avoid recalculating the algorithm or starting extra callback chains alongside them.

2. Choose between useState and useRef

The player keeps time, running and speed in and uses objects for values needed by browser callbacks. Both are created with a React : useState or useRef. The canvas ref is passed to the JSX attribute ref={canvas}. Once React has added the HTML element <canvas> to the page, canvas.current refers to that element; before mounting it is null. By contrast, timeRef.current holds a number: the current animation time in milliseconds. In seek, changing timeRef.current makes the new position available to the next callback, while setTime(next) updates the React interface. setRunning(false) pauses playback. The excerpt omits imports and the JSX markup.

const [time, setTime] = useState(0);
const [running, setRunning] = useState(false);
const [speed, setSpeed] = useState(1);
const canvas = useRef<HTMLCanvasElement>(null);
const timeRef = useRef(0);

function seek(next: number) {
    setRunning(false);
    timeRef.current = next;
    setTime(next);
}

3. Recalculate steps when the input changes

useMemo reuses a calculation while its stay unchanged. This technique is called . The player calculates steps, the sequence of sorting operations, from values and algorithm. It then builds timeline, which selects a frame for a given time through timeline.sample(time). STEP_MS is 650 ms per algorithm step; finalHoldMs: 1000 holds the final state for another second. Time changes require sampling another frame, not calculating all sorting steps again. The excerpt groups three related calculations and omits drawing setup. Each calculation remains safe to run again if React needs to repeat it.

const steps = useMemo(
    () =>
        ({ "bubble-sort": bubbleSort, "insertion-sort": insertionSort, "selection-sort": selectionSort })[
            algorithm
        ].steps(values),
    [values, algorithm]
);
const timeline = useMemo(() => createArrayTimeline(steps, { stepDurationMs: STEP_MS, finalHoldMs: 1000 }), [steps]);
const frame = useMemo(() => timeline.sample(time), [timeline, time]);

4. One requestAnimationFrame chain

requestAnimationFrame schedules one callback before a future screen paint. The tick function schedules the next call only while playback has time left. Its now argument is a timestamp in milliseconds; subtracting previous gives elapsed time, which is multiplied by speed. This avoids assuming every display refresh lasts 16 ms. The first callback only establishes previous. The variable request holds the latest request identifier for cancellation with cancelAnimationFrame. The visibilitychange listener pauses playback when the page becomes hidden. The complete below comes from SortingPlayer; variables such as timeRef and timeline are defined earlier in the component.

useEffect(() => {
    if (!running) return;
    let request = 0,
        previous: number | undefined;
    const tick = (now: number) => {
        if (previous !== undefined)
            timeRef.current = Math.min(timeline.durationMs, timeRef.current + (now - previous) * speed);
        previous = now;
        setTime(timeRef.current);
        if (timeRef.current >= timeline.durationMs) setRunning(false);
        else request = requestAnimationFrame(tick);
    };
    request = requestAnimationFrame(tick);
    const hide = () => {
        if (document.hidden) setRunning(false);
    };
    document.addEventListener("visibilitychange", hide);
    return () => {
        cancelAnimationFrame(request);
        document.removeEventListener("visibilitychange", hide);
    };
}, [running, speed, timeline]);

5. Dependencies and stale closures

The tick callback forms a over values from the render that created its effect. If speed were omitted from [running, speed, timeline], the loop could keep using an older speed. With the current dependencies, React runs the old effect’s before starting its replacement. A speed change therefore cancels the old request and starts one new chain. The next callback reads the retained time from timeRef.current, so playback continues from its current position. With running set to false, the effect schedules no new callback. Required dependencies should stay visible to the linter.

6. Redraw a frame without rebuilding the algorithm

The drawing effect receives frame and passes it to a . The useCanvasViewport Hook returns a ref named viewport; viewport.current holds the used here as ctx. The effect also stores the latest draw function in drawRef.current. The sizing Hook calls it after resizing the canvas, even while playback is paused: assigning canvas.width or canvas.height clears its bitmap. The reduced option follows the visitor’s reduced-motion preference. It displays a completed algorithm state rather than the intermediate bar positions in a transition.

useEffect(() => {
    const element = canvas.current;
    const ctx = viewport.current;
    if (!element || !ctx) return;
    function draw() {
        const sampled = frame;
        const snapped =
            reduced ?
                { ...sampled, current: sampled.progress === 1 ? sampled.current : sampled.previous, progress: 1 }
            :   sampled;
        renderer.render(ctx!, snapped);
    }
    drawRef.current = draw;
    draw();
}, [frame, reduced, viewport, renderer]);

7. Try the site’s player and remove it

The example uses the site’s existing SortingPlayer. Start it, change speed, pause and seek in both directions. The control above the player demonstrates : removing the component runs its effect cleanup, and connecting it again creates a fresh player with the default array and starting position. Hiding it with CSS would not remove it. The switch makes this behavior visible; it does not count renders or measure retained memory.

Up to 24 values. Try duplicates or negative numbers.

Step 0 / 27: Original array. The first element starts the sorted prefix.

Array: [5, 2, 4, 2, 1]

Comparisons: 0 · Writes: 0

Green: sorted prefix. Purple: held value. Highlighted bars: current operation. Positions start at zero.

8. Update React less often when the UI allows it

recordPlayerVideo shows when canvas drawing and React state can update at different rates. It draws a frame on each callback, but sends progress only when more than 150 ms have elapsed since the previous report or when the animation ends. AlgorithmPlayer uses that report for its progress indicator. This is . A heavy interactive scene could similarly keep time in a ref and update its UI less often, provided its slider, description, seeking and final state remain synchronized. That would be a separate change to the sorting player; it is not how it currently works. The excerpt omits the surrounding recording setup and error handling.

video.draw(context, time);

if (now - publish > 150 || time === video.durationMs) {
    progress(time / video.durationMs);
    publish = now;
}

9. Cleanup belongs to the effect that subscribed

The return block from useCanvasViewport stops its and listeners. observer watches sizes, modeObserver watches the player’s expanded-mode attribute, and resolution watches the display pixel ratio. disconnect stops observation; removeEventListener removes the function registered during setup. This effect owns several subscriptions, so after a setup → cleanup → setup check in , only the latest set should remain. Turning off the check or skipping the second setup would conceal incomplete cleanup. The declarations and setup are earlier in the same Hook.

return () => {
    observer.disconnect();
    modeObserver.disconnect();
    resolution.removeEventListener("change", changedResolution);
    window.removeEventListener("resize", update);
    window.visualViewport?.removeEventListener("resize", update);
    context.current = null;
};

10. Cancel asynchronous work as well

Link restoration is : input or the component can change before preparation finishes. In usePlayerLink, every new fragment cancels the previous task through . Cleanup cancels the current task and removes the hashchange listener. The alive flag stops a queued startup task from beginning after cleanup. Here onRestore comes from useEffectEvent, available in React 19.2: the listener can use current committed values without resubscribing for each of them. standalone and algorithm remain dependencies because they determine whether and what to restore. An “is mounted” flag alone would only suppress an outdated UI update; it would not stop the task.

useEffect(() => {
    if (!standalone) return;
    let alive = true;
    let controller: AbortController | undefined;
    const changed = () => {
        controller?.abort();
        controller = new AbortController();
        void onRestore(window.location.hash, controller.signal);
    };
    queueMicrotask(() => {
        if (alive) changed();
    });
    window.addEventListener("hashchange", changed);
    return () => {
        alive = false;
        controller?.abort();
        window.removeEventListener("hashchange", changed);
    };
}, [standalone, algorithm]);

11. Release recorder resources and file URLs

recordPlayerVideo releases recording resources in finally, which runs on success or an exception in the surrounding try. It clears the startup timer, cancels the frame request, removes the abort listener and calls take.dispose(). The player also cancels an active recording when removed. A completed file is available through a . AlgorithmPlayer revokes that address when replacing the video or removing the player, while retaining it for as long as the current file is downloadable. The block below is only the recorder’s final cleanup; its variables and try block are outside this excerpt.

} finally {
    clearTimeout(timeout);
    cancelAnimationFrame(frame);
    signal.removeEventListener("abort", abort);
    take.dispose();
}

12. Verify behavior before counting renders

First check play/pause, speed, seeking, reaching the end, hiding the tab and resizing while paused. Repeat mount/unmount and cancelled exports, then investigate whether callback chains, observers or file references keep accumulating. React Profiler records commits; browser performance tools show work on the main thread, and memory tools help inspect retained objects. Compare equivalent runs and take measurements after cleanup has had time to run. A temporarily larger heap alone does not prove a leak, and does not count React updates. This article’s scheduler tests and visible player checks cover timing and cleanup behavior; no memory or performance benchmark is claimed.