Using D3 for the first time


Time to get your hands dirty! This lesson shows you how to install D3, how to import it — either the full bundle or individual modules — and how to call your first D3 function in a React app.

Members only
4 minutes read

Installing D3.js

Installing D3.js is straightforward — it works like any JavaScript library using npm.

If you're not familiar with this step, I strongly recommend going through the npm lesson in Module B. Otherwise, just type this in your terminal at the root of your project:

npm install d3

That's it! D3 is now part of your project. You can verify by checking your package.json — you should see "d3" listed under dependencies.

Importing and using functions

Once the library is installed, you can import it in any component of your React application using this import statement:

import * as d3 from "d3";

This gives you access to every D3 function through the d3 namespace. For example, you can compute the maximum value of an array:

import * as d3 from "d3";

const data = [4, 8, 15, 16, 23, 42];

const max = d3.max(data);
// 42

Or create a scale that maps data values to pixel positions — something we'll use in almost every chart:

import * as d3 from "d3";

const scale = d3.scaleLinear()
  .domain([0, 100])   // data goes from 0 to 100
  .range([0, 500]);   // pixels go from 0 to 500

scale(50);  // 250
scale(75);  // 375

Don't worry about understanding scales fully yet — there's a whole module dedicated to them! The key takeaway is: import D3, call a function, get a result. That's the pattern.

Full bundle or individual modules?

The import * as d3 from "d3" syntax loads the full D3 bundle — all the core modules at once. But D3 is modular by design, so you can also install and import individual modules:

// Install only the scale module
npm install d3-scale
// Import only what you need
import { scaleLinear } from "d3-scale";

const scale = scaleLinear()
  .domain([0, 100])
  .range([0, 500]);

Here's a quick comparison:

Full bundle (d3)Individual modules
Installnpm install d3npm install d3-scale d3-shape ...
Importimport * as d3 from "d3"import { scaleLinear } from "d3-scale"
Bundle sizeLarger (tree-shaking helps)Smaller, only what you use
ConvenienceVery easy, one installMore installs to manage

Both approaches are perfectly valid. In this course we'll mostly use the full bundle (import * as d3 from "d3") because it's simpler and lets you explore all functions without worrying about which module they come from.

In production apps with strict performance requirements, importing individual modules can reduce bundle size. But for learning and prototyping, the full bundle is the way to go.

Oh no! 😱

This lesson isn’t available just yet.

Take a look at the status badges next to each lesson in the sidebar to see when it’s coming out.

Thanks for your patience! 🙏