Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 44 ยท Real-world Charts and Integration

D3 with React, Vue and Other Frameworks

Combine D3 with React, Vue or Svelte: let D3 own a DOM node via refs, or let the framework render and use D3 only for scales, shapes and layouts.

D3 and modern UI frameworks both want to control the DOM. D3 binds data to elements with selection.join(); React, Vue and Svelte rebuild the DOM from state. Used carelessly the two fight (each overwrites the other's work). Used deliberately they combine very well, because D3 is not one library but many small ones, and most of them never touch the DOM at all.

D3 is a toolbox, not one thing

Part Touches the DOM? Use in a framework
d3-scale, d3-array, d3-format, d3-time-format, d3-interpolate, d3-color no always safe
d3-shape (line, area, arc, pie, stack), d3-hierarchy, d3-force, d3-geo, d3-chord, d3-contour no (they output numbers or path strings) always safe
d3-selection, d3-transition, d3-axis yes restrict to one container node
d3-zoom, d3-drag, d3-brush yes (they attach listeners and sometimes elements) attach on a ref

This table suggests the two integration strategies.

Strategy 1: the framework renders, D3 computes

The framework draws every <rect>, <path> and <text> from state in its normal template. D3 only supplies the math. This is the cleanest option: no DOM conflicts, server-side rendering works, and React/Vue devtools show your chart elements. In React:

JSX
import { scaleBand, scaleLinear } from "d3-scale";
import { max } from "d3-array";

function BarChart({ data, width = 480, height = 260 }) {
  const m = { top: 10, right: 10, bottom: 24, left: 36 };
  const x = scaleBand(data.map(d => d.label), [m.left, width - m.right]).padding(0.2);
  const y = scaleLinear([0, max(data, d => d.value)], [height - m.bottom, m.top]).nice();

  return (
    <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Bar chart">
      {y.ticks(5).map(t => (
        <g key={t} transform={`translate(0,${y(t)})`}>
          <line x1={m.left} x2={width - m.right} stroke="#dee2e6" />
          <text x={m.left - 6} dy="0.32em" textAnchor="end">{t}</text>
        </g>
      ))}
      {data.map(d => (
        <rect key={d.label} x={x(d.label)} y={y(d.value)}
              width={x.bandwidth()} height={y(0) - y(d.value)} fill="#4263eb" />
      ))}
    </svg>
  );
}

You wrote no selectAll or join: React's list rendering with a stable key plays the same role as D3's key function. Import only what you need (d3-scale, d3-array) instead of the whole d3 bundle to keep your build small.

The same idea in Vue uses computed for scales and v-for with :key in the template; in Svelte you declare $derived scales and use {#each data as d (d.label)}. The skeleton is identical: scales are derived values; marks are templated from them.

Animation is where this strategy needs extra care, since React will not animate between two states by itself. Options: CSS transitions on attributes that CSS can animate (transform, opacity, fill), a spring library, or interpolate numbers yourself with d3.interpolate and requestAnimationFrame into state.

Strategy 2: D3 owns a container

When you need D3 behaviours that manipulate the DOM (zoom, brush, drag, complex transitions, axes), give D3 a single node through a ref and let it do everything inside. The framework must not render children inside that node.

JSX
import { useRef, useEffect } from "react";
import * as d3 from "d3";

function ForceGraph({ nodes, links }) {
  const ref = useRef(null);

  useEffect(() => {
    const svg = d3.select(ref.current);
    // ... build the simulation and draw into svg ...
    return () => {
      sim.stop();            // cleanup: stop timers and listeners
      svg.selectAll("*").remove();
    };
  }, [nodes, links]);

  return <svg ref={ref} width={600} height={400} />;
}

Rules for this strategy:

  1. The effect runs after the DOM exists, so ref.current is available.
  2. List every value the drawing depends on in the effect's dependency array.
  3. Always clean up: stop d3.timers and force simulations, remove listeners, disconnect observers. React's StrictMode runs effects twice in development precisely to catch missing cleanup.
  4. Do not store D3 selections in React state. Keep them in the effect or in a ref.
  5. Pass updated data by re-running the effect, or keep a longer-lived chart object (see Reusable Charts) in a ref and call chart.update(data).

In Vue the same code lives in onMounted and onBeforeUnmount with a template ref (const el = ref(null)), plus a watch on the data. In Angular use @ViewChild with ngAfterViewInit and ngOnDestroy. In Svelte use bind:this with onMount and its returned cleanup function.

A hybrid is common

Most production charts mix both strategies: the framework renders marks and tooltips (strategy 1), while a useEffect attaches d3.zoom or d3.brush to a ref and only writes state back (setTransform(event.transform)). The framework then re-renders marks from the new transform. This "D3 handles input, framework handles output" split avoids fights because D3 never creates elements.

A runnable stand-in

The React and Vue code above cannot run inside this page without a build step, so here is the same idea with a tiny hand-written render function playing the role of a component. State goes in, a string of SVG comes out, D3 supplies the scales and the line generator; D3 never touches the DOM.

Strategy 1 without a framework

Change the select: the whole view is recomputed from state. With a real framework only the changed attributes would be patched, but the division of work (D3 computes, the view renders) is the same.

flowchart LR
  subgraph S1["Strategy 1"]
    A1["state"] --> B1["d3 scales + shapes (math)"] --> C1["framework template renders SVG"]
  end
  subgraph S2["Strategy 2"]
    A2["state"] --> B2["useEffect or onMounted"] --> C2["d3.select(ref) draws and animates"]
  end

Choose by who creates the DOM elements.

Choosing a strategy

  • Static or lightly interactive charts, SSR, design-system components: strategy 1.
  • Heavy interaction (zoom, brush, drag, force layouts, complex transitions): strategy 2 or the hybrid.
  • Large data sets: neither; render in canvas (next lesson) and treat the canvas as a ref-owned node.

Common mistakes

  • Letting the framework render children inside a node D3 also appends to. Pick one owner per node.
  • Forgetting the cleanup function, which leaves timers and simulations running after the component is gone.
  • Importing the whole d3 package in a bundle when two small modules would do.
  • Rerunning the whole effect for every tiny state change instead of separating setup from update.
  • Reading ref.current before mount.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In strategy 1 (framework renders, D3 computes), which D3 modules are safe to use freely?

    These modules return numbers or strings, so the framework can use them without conflicts.
  2. 2. What must a useEffect that draws with D3 return?

    Cleanup avoids leaks and duplicated elements, especially in StrictMode where effects run twice in development.
  3. 3. Why should D3 selections not be stored in React state?

    Keep selections in the effect or a ref. State should hold the data that determines what is shown.
  4. 4. What is a common hybrid arrangement for zoomable charts?

    D3 handles the gesture and the framework handles the output, so only one party creates elements.

Summary

  • Many D3 modules only compute; use them inside any framework's templates (strategy 1).
  • When D3 must touch the DOM, give it one ref-owned container and clean up on unmount (strategy 2).
  • Hybrids let D3 handle input and the framework handle output.
  • Import only the D3 modules you need and keep one owner per DOM node.

Next: Canvas Rendering and Performance