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 React calls a component function to calculate the interface. This does not necessarily change the page or repaint a canvas. and applies the result during a React applies a completed render to the page. Several calculations can lead to one commit; counting renders and counting commits are different measurements.. 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 Data managed by React that the component uses to describe its interface. Its setter requests an update; React may skip an update if the value is unchanged. and uses A stable object returned by useRef. Its current property can hold an HTML element, number or function. Changing current does not request a React render. objects for values needed by browser callbacks. Both are created with a React A function such as useState, useRef or useEffect that lets a component use React features. Custom Hooks can combine this logic for reuse.: 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 Values listed in an effect or useMemo dependency array. React compares them with the previous render to decide whether the effect or calculation needs updating. stay unchanged. This technique is called Reusing a calculated result while its inputs stay the same. useMemo can avoid repeated work, but calculations must remain safe to run again.. 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 Code in useEffect that synchronizes a component with something outside React, such as a browser event or animation callback. 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 A function retains access to the variables in the scope where it was created. A callback from an older render can therefore keep using that render’s state or props. 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 The function returned by an effect to undo its setup. React calls it before rerunning that effect and when removing the component. 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 Code that draws a prepared algorithm frame. Here it receives a 2D canvas context and frame data from the timeline.. The useCanvasViewport Hook returns a ref named viewport; viewport.current holds the The drawing interface obtained from canvas.getContext('2d'). It provides methods for drawing and clearing the canvas bitmap. 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 Mounting adds a component instance to the React tree. Unmounting removes it and runs effect cleanup. Merely hiding it with CSS does not unmount it.: 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.
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 Limiting how often an action runs. In this recorder, canvas drawing continues between the less frequent progress updates sent to React.. 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 Browser objects that watch changes. ResizeObserver watches element sizes; MutationObserver can watch changes to HTML attributes. 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 React development checks that can repeat rendering and effect setup/cleanup to expose mistakes. They do not add those extra cycles in production., 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 Work that may finish later, such as preparing a large history. The component or its input can change before the result is ready.: input or the component can change before preparation finishes. In usePlayerLink, every new fragment cancels the previous task through An object that provides an AbortSignal and an abort() method. It requests cancellation; the code doing the work must observe the signal.. 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 A temporary browser address created by URL.createObjectURL for file data held in a Blob. URL.revokeObjectURL releases the browser’s reference when the address is no longer needed.. 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 Frames per second. This describes animation frequency, not the number of React renders or commits. 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.