
This Apress imprint is published by the registered company APress Media, LLC part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.
This book is dedicated to the readers who learn from failures, gain experience, and keep questioning.
Congratulations! You have decided to integrate D3.js with React. There are plenty of ways to learn, such as training courses, YouTube videos, and blog posts, among others. In fact, I am offering an interactive course for integrating React and D3 and it compliments this book very well, as it expands and gives more examples on the topic in this book, check out the course here: https://elielrom.com/BuildSiteCourse .
Much of this information is of good quality; however, each piece is usually based on a different technology stack, and you need to adjust to a different author style or piece the information together to understand it. For these reasons, using this book is a great choice when you want to learn how to integrate D3.js with React, and it will help you understand the concepts deeper. Additonally, we all learn differently, and reading from a book has advantage as you can follow at your own phase and better understand key concepts.
The book teaches you how to work seamlessly with D3.js and React alongside other libraries such as TypeScript. I explain how all these technologies work together and show lots of examples.
This book is set up logically, so you should read the chapters in chronological order. I will build on each topic as you move through the book, and it will be an exciting development journey.
Additionally, there are thousands of libraries that can help expedite your development effort and make your life easier. It can get confusing to pick what libraries to learn and use. In this book, one of my goals was to ease the pain and help you not only pick the best and most popular library but also to give you a rundown of the other options.
My aim is not just to teach you how to integrate D3.js with React. You will learn about tools and libraries that will help you integrate charts to get the job done, and you’ll learn about other technologies and how to join the React community that utilizes the latest and best libraries.
Human nature is choosing the easy way out and learning tools that are easy to master. From my experience, the tools that have a steep learning curve, such as D3.js, are the ones that usually offer more value. They are worth the extra effort you put in to learning them, as knowing these tools makes you a valuable resource.
Choosing D3.js over libraries that are built on top of D3.js is worth the effort. By learning D3.js with React, you can improve the quality of your code as well as potentially earn more as a developer and help tell your “story” better.
You should be comfortable with HTML, JavaScript, and CSS when reading this book, and it’s helpful to have some knowledge of React. That said, I made an effort not to require these proficiencies in the book, and it’s possible to read this book without any prior knowledge; feel free to research the concepts that you are unfamiliar with. A good way to do this is to purchase my other React.js book, React and Libraries ( www.apress.com/gp/book/9781484266953 ). This book can be considered as a continuation of that one. Additionally, I have online courses that I encourage you to take https://elielrom.com/BuildSiteCourse .
In terms of organization, we will create an actual project that includes D3.js and other commonly used components and architecture. I will give you helpful examples, showing you the complete full development cycle. You will learn how to publish your app on a server as well as ensure the quality of the code.
The book code examples can be downloaded from https://github.com/Apress/integrating-d3.js-with-react .
Make sure to read this book and work on the examples to completion. You will become a better React developer, able to complete projects and publish them to the wild, as well as integrate charts with confidence.
Lastly, as a bonus to you and as a thank-you for purchasing this book, you can reach out to me and receive a free ebook that includes many typical React interview questions. You can use these questions to increase your knowledge as well as practice for an interview. See https://elielrom.com/ReactQuestion .
Lots of effort was put into this book from myself, and the editiorial team, however, If you find errors, do not hesitate to point them at https://github.com/Apress/integrating-d3.js-with-react/blob/main/errata.md . Additionally, I would love to hear about any interesting React and D3.js projects. I am available for consulting, coaching, or tutoring: https://elielrom.com/CoachingHourly .
Thanks again for purchasing this book, and let’s get started on your React and data visualization development journey today.

is a React d3 full stack expert. Additionally, he is a technical coach and a coder. As a writer, he has authored and co-authored several technical books. Elad has consulted for a variety of clients, from large corporations such as AT&T, HBO, Viacom, NBC Universal, and Weight Watchers, to smaller startups. Aside from coding, Elad is a PADI diving instructor and a pilot. Visit him at EliElrom.com.
has a background in mechanical engineering from the University of Ibadan, Nigeria, and has been a front-end developer for more than three years working on both web and mobile technologies. He also has experience as a technical author, writer, and reviewer. He enjoys programming for the Web, and occasionally, you can find him playing soccer. He was born in Benin City and is currently based in Lagos, Nigeria.
Integrating interactive data visualization (aka data viz) components can help you tell your story better. React is already set up to be able to animate Scalable Vector Graphics (SVG), HTML, and Canvas; this is nothing new. We’ve had the ability to animate SVG, Canvas, and HTML for years with HTML and pure JavaScript. React has HTML, CSS, and JavaScript capabilities and can play nicely with other libraries to help create charts and animate views.
Business intelligence with data visualization capabilities is becoming more popular because it offers an return on investment (ROI) of $13.01 on every dollar spent (https://nucleusresearch.com/research/single/analytics-pays-back-13-01-for-every-dollar-spent/).
As they say, a picture is worth a thousand words.
Ninety-three percent of communication is nonverbal (https://ubiquity.acm.org/article.cfm?id=2043156).
Our brain processes an image at a speed of 13 milliseconds. Ninety percent of information transmitted to our brain is visual (https://news.mit.edu/2014/in-the-blink-of-an-eye-0116).
Our brains process visuals 60,000 times faster than text (https://carlsonschool.umn.edu/faculty-research/mis-research-center).
High-quality infographics are 30 times more likely to be read than text (https://blog.kissmetrics.com/your-brain-on-visualization/).
Ninety-seven percent of people believe information is more reliably shown by a graph than words and numbers (Cornell University).
React’s biggest advantage over other web platforms is that it uses the virtual DOM (VDOM), which speeds up performance. We can take advantage of what React has to offer as well as other third-party libraries, such as the D3 library and data management, to crunch our data and not just build compelling charts components, but also increase performance. At the same time. Sometimes we want to take control and have our components control the elements instead of React.
Adding other libraries and technologies to the mix, such as Recoil, Material-UI, TypeScript, unit testing, Sassy Cascading Style Sheets (SCSS), and others, will require more knowledge, but it is a small price to pay in exchange for what we get.
In this book, I will give you the tools to learn how to create data visualizations with React, and we will get help from extensive D3 libraries as well as other libraries that are standard in the world of React.
This first chapter serves as an introduction. We will review the tools we’ll use in this book to create animations and charts, as well as set up our first “Hello World” D3/React/TypeScript project. Additionally, we will look at what we can do to ensure quality, looking into unit testing, linting, and formatting.
Let’s get started.
React (also known as ReactJS) is a JavaScript library developed by Facebook (https://github.com/facebook/react) to create user interfaces for the Web.
React was invented by Jordan Walke, who was working on Facebook Ads at the time. It competes with other web frameworks and libraries such as jQuery, Angular, Vue.js, Svelte, etc.
In the previous version of React 16.x, released in September 2017, the React team added more tools and development support while eliminating bugs. The latest version of React (at the time of writing) is 17, which was released in October 2020.
React 17 is a “stepping stone” release, and the release is primarily focused on making it easier to upgrade React to future versions as well as adding better compatibility with browsers. React team’s support shows that the library has great momentum and is not going away any time soon.
React is a favorite among developers. In fact, according to a Stack Overflow survey (https://insights.stackoverflow.com/survey/2020), React is the most loved web framework and has been for two consecutive years.
The need for React developers has ballooned; according to Indeed.com (https://www.indeed.com/q-React-jobs.html), there are close to 56,000 open React developer positions.
The React library is light (around 100KB) and fast.
React is easy to start using.
React can be used as a single-page application (SPA) like with Create-React-App (CRA) or for server-side rendering (SSR) like with Gatsby.js and Next.js.
React can follow unidirectional data flow as well as data binding.
React’s JSX produces better code readability.
React was made to integrate with other frameworks easily.
On its own, React is just a UI library, not a full-blown framework like Angular.
Developers are left to decide which libraries to add and which best practices to follow.
React has a steeper learning curve to master than other tools.
When it comes to creating React applications, there many options to choose from. You can just write the code yourself and then add libraries to help you take care of packaging your code, getting it ready for production (the toolchain), and doing other common tasks that are standard when writing code.
The React toolchain is a set of programming tools used to perform the complex development tasks for our final development/deployment product.
Another option to get started is for you to use the many React starter template projects that already take care of the scaffolding and configurations and include libraries to help you get the job done quickly. The most popular template for creating a React app is Create-React-App (https://github.com/facebook/create-react-app); the project was created by Facebook and has 85,000 stars on GitHub. CRA is based on a single-page application, so there is no page refresh, and the experience feels like you are inside a mobile app. The pages are meant to be rendered on the client side. This is ideal for small to medium-sized projects.
The other option is SSR, which renders the page on the server so the client (browser) will display the app without doing any work. SSR is good for certain use cases, where there is a lot going on and the user experience would be sluggish if the rendering happened on the client side.
CRA doesn’t support SSR out of the box. There are ways to configure and get CRA to work with SSR, but that may be too complex for some developers and involve maintaining the configuration on your own, so it may not be worth the effort.
If you’re building something that needs SSR, it’s better to just work with different React libraries that are already configured out of the box with SSR such as the Next.js framework, Razzle, or Gatsby (which converts a prerendered website into HTML at build time).
If you prefer SSR with React check out Next.js, Razzle, or Gatsby.
With that being said, with CRA you can do prerendering, which is the closest you can get to SSR, as you will see in later chapters of this book when we optimize our React app.
In this book’s examples, we will be using CRA; however, the components we will be building are loosely coupled and can be easily imported into any React project with little or no effort.
We will be using CRA in this book, and the projects will be easy to follow. However, feel free to use any React template starter project or even create your React project from scratch and handle your own toolchain. In Chapter 10, I will show you how to set up your project with React using SSR with Next.js.
The libraries we will be installing are submitted to NPM (https://www.npmjs.com/). Node.js is needed to get NPM, and NPM is used to download packages from the NPM repository.
NPM and Node.js go hand in hand. NPM is the JavaScript package manager and is the default package manager for the JavaScript Node.js environment.
If you don’t have Node.js installed, you will need to install it. Node.js needs to be at least at version 8.16.0 or 10.16.0. The reason we need that version is we need to use NPX, which is an NPM task runner introduced in 2017 that is used to set up CRA.

Downloading Node.js on a Mac
The installer recognizes your platform, so if you are on a PC, it’s the same steps.
The command will output the Node.js version number.
To download packages from the NPM repository, we have two options: Yarn or NPM. NPM comes with Node.js and can be used without installation. However, in this book, we mostly will use another library: Yarn. We will be using Yarn as much as possible for downloading packages instead of NPM.
The reason we will be using Yarn instead of NPM in this book is that Yarn is faster than NPM. Yarn caches the installed packages as well as installs packages simultaneously. We have NPM installed as well because it comes with Node.js.
Equipped with Node.js as well as NPM and Yarn, we are ready to get started. We can use the CRA Must-Have-Libraries (MHL) template project I have created for you at https://github.com/EliEladElrom/cra-template-must-have-libraries.
Type checker: TypeScript
Preprocessors: Sass/SCSS
State management: Redux Toolkit/Recoil
CSS framework: Material-UI
CSS-in-JS modules: Styled Components
Router: React Router
Unit testing: Jest and Enzyme + Sinon
E2E testing: Jest and Puppeteer
Folder structure
Generate templates
ESLint and Prettier
Other useful libraries: Lodash, Moment, Classnames, Serve, react-snap, React-Helmet, Analyzer Bundle
If you want to understand how these libraries were installed, you can create your own template or modify an existing one. That is beyond the scope of this book; however, you can read this article for a complete step-by-step installation of each library:
Or you can take my course on Udemy:
https://www.udemy.com/course/getting-started-react17-with-must-have-libraries/
Once the installation of libraries and all the dependencies have completed downloading, you can run the project by starting a local server.

CRA compiled successfully
You can see this run command in the package.json file. The command points to the react-scripts library and starts the project on a local server on port 3000 as the default (which you can change).

Local server running CRA starter project
When it comes to writing React code, there are two options to choose from: you can write your code using JavaScript (JS) or TypeScript (TS). TypeScript is a transpiler, meaning ES6 doesn’t understand TS, but TS gets compiled down to standard JS, which can be done with Babel.
The CRA MHL project is already set up with TS as a type checker out of the box, so there is nothing you need to do. However, I want to expand a bit on why I picked TS over JS.
Did you know that TypeScript is an open source programming language developed and maintained by Microsoft?
According to Stack Overflow’s 2020 survey, the TypeScript programming language is the second most popular, surpassing even Python last year!
Why is TypeScript so popular?
TS, as the name suggests, is all about setting “types.” TS is easier to debug and test than JS and prevents potential problems by describing what to expect (you will see that when we test our components later in this book). Using TS, a full blown object-oriented programming (OOP) language and modules brings development to a more professional level and increases our code quality.
TypeScript is an OOP; JavaScript is a scripting language.
TypeScript uses static typing following the ECMAScript specification.
TypeScript supports modules.
A type system associates a type to each value—by examining the flow of these values, it ensures there are no type errors.
Static typing means that types are checked before runtime (allowing you to track bugs before runtime).
JS includes only the following eight dynamic (at runtime) types: BigInt, Boolean, Integers, Null, Number, Strings, Symbol, Object (objects, functions, and arrays), and Undefined.
All these types are called primitive types , except for Object, which is called a nonprimitive type . TS adds static types to JavaScript by setting a compiler to type-check the source code to turn it into dynamic code.
React and TypeScript work nicely together, as TypeScript improves the code quality of your app using OOP best practices, so it’s worth the learning curve.

TS Playground
The TS Playground site has plenty of examples that can help you better understand TS. I recommend exploring these examples.
Notice the example uses “strict,” and in the TS Config menu item, you can set the compiler options. The different compiler options are explained at https://www.typescriptlang.org/docs/handbook/compiler-options.html.
It may be antagonizing writing your code with errors and warning popping up left and right at compile time, but it is worth it as it will help you avoid issues later when the compiler can’t figure out the types and your app breaks during runtime.
We would rather our app breaks during compile time than runtime.

Specify the ECMAScript (ES) target in the TS playground
D3 includes a comprehensive library with close to 170 examples. See https://observablehq.com/@d3/gallery.
D3 takes advantage of these base technologies: JavaScript, HTML, CSS3, Canvas, and last but not least SVG.
D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.
D3 is written in JavaScript and focuses on attaching data to Document Object Model (DOM) elements.
Attach: Attach data to DOM elements.
Display: Use CSS, HTML, and/or SVG to display data.
Interactive: Make data interactive with the use of D3 data-driven transformations and transitions.
The latest version at the time of writing is v6. Read the changelog (https://github.com/d3/d3/blob/master/CHANGES.md) to see what’s new in version 6.
D3 has a steep learning curve, and adding React and TypeScript to the mix makes the curve even steeper.
Keep in mind that with TS, we need to bring in the types as well (yarn @types/module-name).
When you look at examples on the Web such as the ones at https://observablehq.com/@d3/gallery, it’s important to check the D3 version used in that example. D3 v4 and up have gone through a major change, and upgrading requires good knowledge of the D3 libraries.
Recharts: https://github.com/recharts/recharts
Visx : https://github.com/airbnb/visx (examples: https://airbnb.io/visx/gallery)
Nivo: https://github.com/plouc/nivo (examples: https://nivo.rocks/components)
React-vi: https://github.com/uber/react-vis
Victory : https://github.com/FormidableLabs/victory (examples: https://formidable.com/open-source/victory/gallery)
Semiotic: https://github.com/nteract/semiotic ( examples: https://semiotic.nteract.io/examples)
react-d3-components : https://github.com/codesuki/react-d3-components (examples: https://github.com/codesuki/react-d3-components#examples)
In Chapter 9, I will show you how to implement some of these popular libraries as well as review the libraries to help you pick one.
Many will argue that the last thing we need is another chart component library, and they are right. If you need ready-to-use charts, there are plenty to choose from.
With that said, creating truly innovative and performant visualizations may be a challenge using a chart library, and you will likely find yourself needing to use D3 or fork an existing chart library and make changes.
In addition to D3 and React libraries, there are other high-level libraries that you can use such as Vega (https://vega.github.io/vega-lite/).
Additionally, there are business intelligence (BI) tools such as Tableau or PowerBI that you can use to analyze data as well as integrate that visualization into your React project.
Keep in mind that besides the top libraries I mentioned, GitHub is littered with failed attempts to make the ultimate chart library. You will quickly drown in options, flags, and props to satisfy all the use cases.
D3 is the ultimate “chart lib.” If you want to do a customized data visualization, take the time to learn D3.
With that being said, there are specific projects that require a quicker release or greater customization such as proof-of-concept (POC) projects. In these cases, knowing what’s out there and how to integrate or fork it will come in handy, so I will cover some of these libraries for your reference in Chapter 9.
Besides D3, ReactCSSTransitionGroup is one example of a React library that provides a high-level API based on ReactTransitionGroup. It is an easy way to perform CSS transitions and animations when a React component enters or leaves the DOM (the library is inspired by Angular’s ng-animate).
You can use this library as well as others in conjunction with other libraries such as D3; you can learn more about it here: https://reactjs.org/docs/animation.html.
We have covered our starter project called react-d3-hello-world as well as looked at TypeScript and D3, so we can now put it all together and create our first “Hello World” D3 project.
HelloD3.scss
HelloD3.test.tsx
HelloD3.tsx

HelloD3 components

CRA MHL D3 “Hello World”
Congratulations, you just created your first project that integrates React with D3.
Refs provide a way to access DOM nodes or React elements created in the render method.
Notice that the TS type is set to HTMLDivElement. How do I know that? I had to dig into the React code to find out the ref object type. This is common practice when using TS, and I find it helpful to dig inside the actual React libraries as it increases my understanding of React.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
Our draw() method consists of “selecting” or choosing the HTML element we will be using. Next, we “append” or in other words add a text element that says “Hello World.”
Throughout the book I will often be using the draw() function and not listing the draw() function as dependent in useEffect. The best approach is to memorize the draw object with useCallback to ensure there won’t be an infinite loop (see https://reactjs.org/docs/hooks-reference.html#usecallback). If you are unfamiliar with this method, I will be covering this when I show you how to optimize in Chapter 11 (the Memorize function with useCallback).
What’s happening here is that we have a rectangle in the size of 500×500px and then D3 overlays another rectangle in the size of 250×500px, which takes half the size of the React JSX rectangle.
This example is simple and doesn’t show why we would need D3 as we can just write this text and these rectangle elements in JSX and have our code be more readable.
However, this is a simple minimalist “Hello World,” intended to help you understand the working pieces, and later in this chapter, you will see the power of d3.HelloD3.scss.
Our project comes out of the box with SCSS, and Webpack is already configured with the SCSS loader, so in addition to CSS, you can just use SCSS without configuring anything.
If you haven’t used SCSS before, you may be asking, why am I using SCSS and not CSS?
Cascading Style Sheets (CSS) is a core functionality in HTML, and you need to familiarize yourself with CSS if you are not already. This goes for working with HTML in particular and with React specifically. On large projects, CSS preprocessors are often used to complement CSS and add functionality.
There are four main CSS preprocessors that are often used with React projects: Sass/SCSS, PostCSS, Less, and Stylus.
CSS is used to represent the visual layout of the web page on different devices. CSS preprocessors are often used to enhance CSS functionality.
The quick answer is that Sass/SCSS is better for the majority of today’s projects, so that’s what we will be using.
Sass/SCSS is the most popular and will probably lead you to the best paying jobs as a developer according to surveys (https://ashleynolan.co.uk/blog/frontend-tooling-survey-2019-results). Sass/SCSS is considered a well-known tool. If you want to learn more and see a comparison between the different CSS preprocessors, check out my article on Medium: http://shorturl.at/dJQT3.
The code is using the Jest and Enzyme libraries. Jest comes out of the box with CRA and Enzyme, and Sinon comes out of the box with MHL, so there’s nothing you need to do on your part to get that configured.
Why Jest and Enzyme + Sinon?
Jest is a JavaScript unit testing framework and the standard for React applications. It was built to be used with any JavaScript project, and it comes with CRA out of the box. However, we do need Jest-dom and Enzyme to enhance the capabilities of Jest.
Another must-have library that we should be aware of and add to our toolbox is Sinon (https://github.com/sinonjs/sinon).
Jest and Sinon serve the same purpose, but there are times that you may find one framework more natural and easier to work with for the specific test.

The unit testing tests passed
As you make changes to your component, make sure to update the unit testing file as well as test different portions of the component functionality.
As I mentioned earlier, if you want to understand how these libraries were installed, you can create your own template or modify one. That is beyond the scope of this book; however, you can read this article for the step-by-step installation process of each library:
Or you can take my course on Udemy, which includes a 40-page ebook to help you understand all the moving pieces and how they were installed and configured:
https://www.udemy.com/course/getting-started-react17-with-must-have-libraries/
HelloD3Class.scss
HelloD3Class.test.tsx
HelloD3Class.tsx
Let’s review HelloD3Class.tsx .
The difference is that we set the reference object before we set the constructor; then on the constructor level we can initialize the reference object.
Once the component lifecycle event componentDidMount is called, we can append our elements to the DOM.
All code in any code-base should look like a single person typed it, no matter how many people contributed.
—Rick Waldron
Luckily, this can be done.
Lint is a tool for analyzing your code. It is a static code analysis tool created to identify problematic patterns found in code. Prettier is an opinionated code formatter.
Linting is the process of running a program to analyze your code to find potential errors.
Lint tools can analyze your code and warn you of potential errors. For it to work, we need to configure it with specific rules.
Arguments over style are pointless. There should be a style guide, and you should follow it.
—Rebecca Murphey
Airbnb—as part of its style guide—provides an ESLint configuration that anyone can use and become the standard.
ESLint is already installed on CRA MHL template, but it’s optimized with a styling guide you don’t need to do a thing to enjoy using it.
The project is already set up with ESLint and Prettier for TypeScript using Airbnb’s styling guide (which is considered the standard).
However, if you want to understand better, read my article at https://medium.com/react-courses/react-create-react-app-v3-4-1-a55f3e7a8d6d to set up your project with ESLint and Prettier for TypeScript using Airbnb’s styling guide.
.eslintrc: ESLint run commands configuration file
.eslintignore: ESLint ignore files
.prettierrc: Prettier run commands configuration file

Output after running the lint command

Output after running format
In this chapter, I introduced you to the tools that we will be using throughout this book.
We talked about React and its advantages and limitations. We set up our starter project using CRA and the MHL template project and looked at TS, SCSS, unit testing, formatting, and linting. I also touched briefly on D3, ReactTransitionGroup add-ons, and other data viz libraries available to use.
We created our first “Hello World” project with React and D3 using TS as a function component as well as a class component, and we ensured its quality with testing, linting, and formatting.
Quality is important generally, and even more so when working with charts and animations as the resource. Low-quality code can cause a degraded user experience as many charts use large data sets (memory usage), as well as lots of CPU power, to render on the client’s machine.
In the next chapter, we will continue learning how to create React components that utilize D3 to perform tasks such as drawing graphics, creating animations, and handling user interactions events.
In this chapter, I will show you what your options are and break the process of creating charts down into smaller chunks so you can understand the process better before diving deeper and creating charts. The process can be broken into three layers: data, view, and user interaction.
At any part of these layers, you can use React, D3, or any other libraries that integrate with React. Having options is great; however, it can also be confusing to decide what to use and when. Understanding your options is important as it helps you make an educated decision.
Graphics
User gestures
Animating
In the first portion of this chapter, I will show you how to create graphics with HTML and SVG elements using both React function components and class components. We will utilize React’s JSX as well as D3. We will consume data and draw elements. In the last portion of this section, we will create our first simple chart.
In the second part of this chapter, I will show you how to set mouse events, both in React and in D3.
Lastly, we will learn about animating graphics using React and also how to animate with D3.
By the end of this chapter, you will understand what your options are when it comes to drawing, setting events, and animating graphics. Along the way, I will show you options for setting up function and class components, and we’ll talk a bit about component lifecycle hooks. Also, I will give you some tips.
Let’s begin.
As I mentioned, to create a data visualization component, the process can be broken down into three main layers: data, view, and user interactions.
Let’s take a look at what each layer includes.
Get the data.
Set the data.
Process the data.
Integrate with the React lifecycle hooks.
Draw a chart.
Style the component.
Add transitions.
Handle user gestures.
When drawing charts, a good place to start is with the data. You need to see what story the data is telling. Once you understand the story, it’s time to select a chart. There are many different ready-made chart libraries you can integrate, and you can also create your custom solution with D3. Your options are limitless. No matter what you decide to use, understanding the basics of how everything works is crucial.
As you probably know, React JSX code may look a lot like HTML, but it is not. It’s JavaScript extension (JSX) code.
JSX is a React extension that uses JavaScript tags that mimic HTML code, so the code is mostly similar to HTML, but it is not HTML.
To understand why React is using JSX instead of just pure HTML, we first need to talk about the Document Object Model (DOM). React processes your JSX code in the background before committing these changes into the user’s browser to speed up how quickly the user’s page loads.
The Document Object Model (DOM) is an in-memory representation of HTML and is tree-structured.
Scalable Vector Graphics (SVG) is an XML-based markup language for describing two-dimensional-based vector graphics. As such, it's a text-based, open Web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including CSS, DOM, JavaScript, and SMIL. SVG is, essentially, to graphics what HTML is to text.
SVG elements include many different types of graphics, and each element has its own set of attributes from an image to a circle, a line, a text element, a rectangle, a group, and so on. Even the most seasoned HTML developers are unaware of all the SVG elements and properties in the SVG API.
To learn more about SVG, you can see the complete list of available SVG tags here:
https://developer.mozilla.org/en-US/docs/Web/SVG/Element
I recommend you bookmark this page and reference it when needed.
However, I want to point out there are other ways to draw graphics. For example, we can use the HTML <canvas> element via JavaScript. The <canvas> element is a container for graphics.
SVG gives better performance with a smaller number of objects or a larger surface. A canvas gives better performance with a smaller surface or a larger number of objects.
A canvas can become blurry, and the device pixel ratio needs to be checked and adjusted. To avoid blurry images with different device pixel ratios, check out the Mozilla documentation here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
SVG allows styling with CSS; a canvas can only be changed through scripts.
SVG is vector-based; a canvas is raster-based (a rectangular grid of pixels).
SVG gives better scalability than a canvas, so once an element needs scaling, SVG is preferred.
SVG has a performance advantage over a canvas for a larger screen and a low number of objects; however, if you work with a smaller screen size and many objects, a canvas is better.
A canvas (https://www.w3schools.com/html/html5_canvas.asp) can be used to draw components in HTML. In fact, not only can you use a canvas to draw components, but you can also animate it and manipulate the element attributes. The React JSX version of a canvas is no different.
Let’s create an example. We can use the same project we created in Chapter 1 (react-d3-hello-world) and add a component that will include a canvas. You can download the final code of all the examples of this chapter from the book’s repository.
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch02
In our JSXCanvas component, we will use the canvas JSX component, which matches the HTML canvas. We will change the attributes to change the color of the canvas to be tomato red.
We will be using the ref object and useEffect. We first create a reference to our canvas.
Once the component is initialized, we can set the useEffect method.
What is useEffect? useEffect is called after the rendering process is completed. useEffect checks dependency values from the last render and will call your effect function if any one of them has changed.
The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of an <canvas> element. It is used for drawing shapes, text, images, and other objects.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
There is another way to write less code in regard to the reference. Instead of defining the variable and then assigning it in the component, we can do that inline. Let’s take a look.
However, this is not the cleanest code since we are not supposed to return the assignment according to best coding practices; however, that’s why I am disabling the ESLint from complaining by adding an eslint comment . This approach is not recommended, though, because of the ambiguity of the code; I wanted you to see these options.

Canvas drawing manipulated to size and color we selected
However, SVG would give better results if you wanted that crispy print quality on all devices or you needed scaling such as for zooming functionality. I am not going to dive deeper into canvas as I recommend staying with SVG; however, I wanted you to be aware that it’s possible, and if you ever have a use case that needs a canvas such as in a case targeting a smaller screen size and many objects, you will have it in your toolbox.
Notice that I am using the transform attribute . The transform shifts the group element to top left corner. You can read more about the transform attribute in the Mozilla documentation.
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
The transform attribute can be used for many things such as rotate, scale, and skews.
For example, if we want to implement the example from the Mozilla docs (https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform). The example is using xlink to assign an SVG path to an element for reuse in order to create a heart shape and a shadow effect. Unfortunately, you will often see that you cannot just copy and paste most code you will see online (D3 related or not) into React without some level of modification and knowledge of what you are doing.
The code will generate the error “Type { xlink: true; } is not assignable to type SVGProps<SVGUseElement>.”
The assignment to useTag is done using dangerouslySetInnerHTML.
In our case, we know what we are doing, and we are not passing some runtime string that can cause an injection attack, so we are fine.

Using SVG with xlink
To make it more realistic and interesting than just using SVG, we want to now pass data from the parent component using React props and draw the data using the HTML p tag with some straightforward React code. Let me show you how it’s done.

Mapping data example using React code
I am showing you how to use the p HTML tag to simplify things, but this could be an SVG element such as a circle or a rectangle, as I will be showing in the other examples.
The previous example was pure, straightforward React code. In this example, let’s add D3 to add a map and draw for us. Let’s call the component HelloD3Data.

Mapping data example using D3 and React code
As you can see, when comparing the two examples of iterating through data between React and D3, D3 doesn’t look as intuitive as React. Our example is simple in nature, but when there is a need for lots of calculation and a large data set, D3 will start to shine.
So far, we have worked with simple examples and manipulated HTML elements such as <canvas>, p tags, and div. Additionally, we have worked with SVG and D3.
This time let’s create our chart with a class component instead of a function component so you can see the difference.
I want to point out that it’s preferred to extend React PureComponent when you don’t need the shouldComponentUpdate life cycle event.
React.PureComponent gives a performance boost in some cases in exchange for losing the shouldComponentUpdate lifecycle hook. You can read about it more in the React docs (https://reactjs.org/docs/react-api.html#reactpurecomponent).
In the class constructor, I am setting the interface, creating the reference, and setting the data.
As you recall from previous examples of function components, we called the draw function. In the React class component, we can call the draw method during the componentDidMount lifecycle hook.
The componentDidMount() lifecycle hook is part of the mounting phase and can be overridden with class components. Any actions defined within a componentDidMount() lifecycle hook are called only once when the component is first mounted.
On the drawChart method , I will take help from D3. I first select the reference, then add an SVG element using the append, and finally set our width and height.
We are using the D3 select on the element class name in some examples while using a reference in other examples. Using a class name as a reference works fine in our examples; however, there are cases where we want React to control our component, and that’s where setting a reference is better as React knows about changes in the element. Such a case would be on a list: array.map((item: object) => ( <ListItem item={item} /> ))}. React iterates through a list, and if we use a map to render the list and that component is not using reference, the calculations can be off.

Simple bar chart using React and D3
Congratulations, you just created your first chart—a bar chart!
When it comes to React, you really want to familiarize yourself with React’s version 16.9 and up lifecycle hooks as they have changed since version 16.9. Having a solid understanding of React’s lifecycle hooks can help ensure changes to the DOM are made only when needed to tie in better with React’s VDOM paradigm and make sure your component is optimized.
Mounting phase: The component is created to start its unidirectional data flow journey and make its way to the DOM. It uses constructor(), and the following methods: static getDerivedStateFromProps(), render(), and componentDidMount().
Updating phase: The component is added to the DOM, updates can be rerendered on a prop or state change. The events are: static getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), componentDidUpdate().
Unmounting phase: This is the final phase of a component’s life cycle. The component is destroyed and removed from DOM.componentWillUnmount().
In React 17, the access to the previous methods such as componentWillMount was deprecated, and you should be using the new hooks to access the component lifecycle. It includes getDerivedStateFromProps, getSnapshotBeforeUpdate, componentDidMount, and componentDidUpdate.
User interactions with graphics are not different from user interactions with any of the React components. React JSX aligns itself to HTML and SVG when it comes to mouse events.
However, you still have options for how to tap into these events.
You can use the JSX events or use D3. When to use a tool depends on what you are building. If you use D3 to create the graphics, you will need to also use the D3 events; however, if you use JSX to create your graphics, you can use either JSX or D3. The choice is yours.
For these reasons, I will show you both approaches. Let’s take a look.
Notice that I am using React.MouseEvent instead of the standard HTML’s MouseEvent.
In React, events are the triggered reactions to specific actions like mouse hover, mouse click, keypress, etc. Handling events in React is similar to handling events in DOM elements. But there are some syntactical differences.
SyntheticEvent , a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.
Events are named using camel case instead of just using the lowercase. Here are two examples: React.KeyboardEvent and React.MouseEvent.
Events are passed as functions instead of strings. If you follow the code, you can see that React events extend UIEvents, which extends SyntheticEvent.
React uses its own event system. That’s why we can’t typically use MouseEvent from the standard DOM.
We need to use React’s events; otherwise, we get an error, or we just won’t be able to access methods. Generally speaking, most events are mapped with the same name.
Luckily, React’s typings give you the proper equivalent of each event you might be familiar with from standard DOM.
We can either use React.MouseEvent or import the MouseEvent typing from the React module.
In the next example, I am going to replicate the same functionality from the previous example, setting a circle with mouse events; however, this time, I will be using D3 instead of React JSX. Let’s take a look.
My draw() method will select my SVG wrapper element and then append a group element and a circle element and set the events using the .on method on D3.
I am even attaching the same class circle in this example.
React JSX calls the class attribute className, and in D3 the attribute matches HTML SVG, so it would be class.
As you can see, for most people, React JSX is more intuitive and easier to read; however, if you need to write D3 code, you need to use the D3 event, and it will be straightforward once you understand what you are doing.
Knowing both options gives you flexibility and more control over your code. When we want d3 to be in charge of the DOM for our component, it’s better to use React elements and tie as much as possible to React. In cases that we need to take over the task of handling the DOM, having d3 can help us.
In this section, I will cover another part of the interaction layer: creating animations. We may want to create a transition when we change the data or show a change of data over time, and we can do that in a more elegant way with animations, or transitions.
CSS transitions : We can use plain old CSS using CSS transitions either as part of the style sheet or dynamically using style={{someCSSPropertyExample: 50}}.
CSS-in-JS modules : If you use libraries such as CSS-in-JS modules, you can set transitions in an intuitive way.
D3 transition : D3 also offers transitions using the Transition API.
While we develop charts, we will be using transitions, and just as we saw with events, it’s good to know our options.
I will show you both CSS-in-JS modules and D3.
CSS-in-JS modules are a popular option for styling React applications, because they integrate closely with React components and have features that allow you to change properties passed from the parent component or tie properties from the state.
Indeed, the CRA MHL library project is set up with Material-UI and Styled Components out of the box, so you don’t need to install anything; we can just start using both Material-UI and Styled Components.
For example, we can change our style based on React props. Also, by default, most of these systems scope all styles to the respective component being styled.
There are many options to pick from when it comes to CSS-in-JS modules such as Styled Components, Emotion, and Styled-jsx.
I picked Styled Components because it goes hand in hand with Material-UI; you can read more about it (if you are unfamiliar) at https://styled-components.com.
But wait, why do we need Styled Components? Doesn’t Material-UI have a styled import similar to Styled Components already?
Yes, it is true that Material-UI is a great component library that emulates Google’s Material Design and has a built-in styling mechanism. So why is it not enough? The quick answer is that the Material-UI CSS-in-JS solution doesn’t feel as powerful as Styled Components. Material-UI was designed to be used from the get-go with its own styling solution, CSS-in-JS. But sometimes you want other features that are not available in Material-UI style, or you are like me and just like Styled Components better.
Fortunately, Material-UI did make it simple to use other styling solutions.
Styled Components is another great library used to style React components. That’s done by defining React “styled” components without CSS classes. Styled Components is best used when you want to write regular CSS, pass functions, and props. You may ask, why not just use Styled Components then?
There aren’t many mature libraries out there that are at the Material-UI level at the time of writing, certainly not at Material-UI maturity levels.
We can leverage the advantages of both Material-UI and Styled Components together.
Render CSS conditionally using props
SCSS support
Template literal syntax for CSS
And much more.
For one of the charts we will be using later in this book, we will need a pulsating circle. The pulsating circle can be used to highlight something on a chart.
On the rendering side, we can just use StyledInnerCircle , which we created as a JSX component.

Pulsating circle using React Styled Components
In terms of animating with D3, the process follows an animation sequencing. If you are familiar with any animation software, you will find D3 more intuitive since you understand the concepts of animation. For others, this can be confusing.
As an example, let’s create another pulsating circle, but this time let’s use D3.
To keep a loop, I will be creating a function called repeat() . That function will select the circlSVGvg element (I am creating the circle in JSX; by now you know what to do if you want this to be 100 percent pure D3).
Next, I will be setting a transition.
During the first 300 ms, I first set the attributes of the stroke to 0 and then set the duration and change the stroke opacity from 0 to 0.5.
Next, I set another stroke to change and use the D3 ease to create sinus ease (yes the same sinus circle we used in math class) in the animation.

Pulsating circle using D3
You can see that the idea is to sequence the animation. I am sure some will find this more complicated, while others will find it easier than the previous example.
Graphics
User gestures
Animating
In the first section, I showed you how to create graphics with HTML and SVG elements using React function and class components.
We used both React JSX and D3. We consumed data and drew elements. We even created our first chart, a bar chart.
In the second section, you learned about setting events with D3 and React and about animating graphics using React and D3.
As you can see, when it comes to drawing, consuming data, animating, and even interacting with options, you can use React, D3, or other libraries. That’s what makes D3 with React unique. These sets of options really come in handy when it’s time to integrate your charts into existing code, to test it, and to work with different member teams that hold different skill sets; it even makes your code more readable.
In the next chapter, we will start creating simple charts such as line, area, and bar charts as well as consume data and animate and interact with these charts.
Line chart
Area chart
Bar chart
Let’s begin.
You can download the entire code of this chapter from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch03
The first chart I will show you is a line chart. A line chart shows graphically quantitative data and is considered as one of the most basic types of charts. The line chart consists of three drawing elements: the x-axis, the y-axis, and a line.
Fortunately, D3 has methods to help you through the entire process of creating a line chart.
A good place to start is the data. For the line chart, the data I will be using is straight from Yahoo Financing. I will be pulling historic data for the Boeing stock, with a ticker notation of BA: https://finance.yahoo.com/quote/BA/history. Once you get to the page, you will see an option to download the data.

CSV file of historical stock prices for BA, opened in Microsoft Excel

Formatting date of CSV file that contains BA historical stock prices
I am taking the price history of BA and then converting the CSV to two fields: data and value .
Lastly, I am renaming the Date and Open columns to date and value.
BasicLineChart.scss: SCSS style file
BasicLineChart.test.tsx: Jest/Enzyme test file
BasicLineChart.tsx: Component
types.ts: TS types
The function component BasicLineChart does the heavy lifting, and it will draw the axis and line chart.
I will be importing React, SCSS, D3, and the types file. The structure is the same as we had in the previous chapter.
I am using d3.extent and casting my domain as [Date, Date]. d3.extent returns the min and max simultaneously. I also change the range from zero to the width of the chart.

ESLint error message due to incompatible types
The call method is a common way for D3 to return a reference to itself in the form of a selection.
What’s happening here is that svg.append('g') appends an SVG group element to the SVG and returns a reference to itself in the form of a selection.
When we call on a selection, we are calling the function axisBottom on the elements of the selection g. We are running the axisBottom function on the newly created and appended group, g.
Notice that these D3 scale methods really helped a lot; they were able to do the calculations and transform our data into the values needed to draw the chart.
If I need to add a pulsating dot or anything on the basic line chart, what I can do is reuse these x-axis and y-axis values, for example y(300).
For testing, I am using Jest and Enzyme to ensure that the component mounts and uses the props I set.

Line chart of BA stock price
I am not getting into details on how the format, lint, and test got set, but as I pointed out before, you can learn more about these in my React and Libraries book, available at https://www.apress.com/gp/book/9781484266953.
If you don’t set the test suites, it’s fine and won’t affect any of the functionality; however, it is just good practice to write your component with full testing coverage.
The area chart shows graphically quantitative data and is similar to the line chart.
The difference is that the area between the axis and the line is emphasized with color.
In terms of coding, it is similar to the line chart we just did in the previous example; the only difference is that the area is colored
As for the data, I will be using the S&P 500 ticker and format the data just as I did in the line chart (https://finance.yahoo.com/quote/%5EGSPC/history).
This code is in addition to the path line since I need to fill the area with color.

BasicAreaChart files structure

BasicAreaChart complete
As you saw, both the line and area charts were similar. Once we understand the processes of retrieving and formatting the data, creating our axis for both x and y, and drawing our chart, it starts to get easier each time you draw a chart.
The last chart I will be creating in this chapter is another commonly used type of graph, a bar chart.
Bar charts are used to display and compare numbers, or frequency, or another measure. Bar charts are popular because of how simple they are to create, and they are easy to interpret.
I already showed you how to create a simple bar chart in Chapter 2; however, the bar chart didn’t have an x,y axis, and the data wasn't loaded from an external file.
In this example, for the data, I will be using the Stack Overflow survey data that shows the popularity of React and other frameworks: https://insights.stackoverflow.com/survey/2020. This chart helps you choose a web framework.
Set up types.ts, scss, and BasicAreaChart.test.tsx just as we have done in the other examples.
Looking at the chart, you can see that the chart tells a story. At first glance, the 2020 Stack Overflow results appear that React has bypassed Angular by almost 11 percent.

However, that is not the case.
The survey includes React.js and Gatsby separately, although they are both based on React, and there is also a split between Angular and Angular.js.
In reality, if we add these results together, it is almost an exact split between Angular at 41.2 percent, React at 39.9 percent, and jQuery at 43.3 percent.

React versus Angular versus jQuery 2020
If you interested in seeing a comparison between using React and Angular, check out my article on Medium at https://medium.com/react-courses/angular-9-vs-react-16-a-2020-showdown-2b0b8aa6c8e9.
The 2021 Stack Overflow results have not been published at the time of writing this book, but it would be interesting to see how these values change over time. Now that you are equipped with this chart, you can plug in the new data.

Test suite results passing for all charts
Line chart
Area chart
Bar chart
I showed you how to utilize D3 for the fullest not just for drawing but even to retrieve data, and I showed you how to avoid common ESLint error messages due to the TS requirement to have the types. I also gave you some tips in terms of how to organize your composition and run a quality check with the format, lint, and test run scripts.
Check my d3 and React interactive course to see other ways you can implement all the examples in this chapter with different approaches. The interactive course covers more topics for this section, such as, taking more control over the DOM, color spaces, interactivity, design, as well as expanding on what’s in this chapter. The course compliment this chapter and book neatly; https://elielrom.com/BuildSiteCourse
Pie chart
Scatter plot
Histogram chart
As you have already seen, D3 is the standard for creating charts, so if you are serious about creating and customizing charts, you can’t escape learning about D3. React is made to integrate with other libraries such as D3; however, adding TypeScript to the mix does require special attention.
In the previous chapters, I showed you how to create popular and basic types of charts with React, TS, and D3. Additionally, if you took my React + d3 interactive course (https://elielrom.com/BuildSiteCourse) you seen other ways you can implement all the examples in the previous chapter with different approaches such as applying memorizing callbacks, handling resizing, more interactions, and handling the DOM. That combo of React + d3 + TS needs some special attention versus using just JS, and the basic charts in this chapter and the previous one reflect things that I have found to work the best.
In this chapter, I will be covering how to create more simple charts with React and D3 using TypeScript as a type checker.
Pie chart
Scatter chart
Histogram chart
Let’s begin.
A pie chart is one of the most basic and popular types of chart. The type of chart is a circular, statistical graphic. A pie chart represents numbers by using slices to represent a proportion of the whole.
BasicPieChart.tsx: Main component
BasicPieChart.test.tsx: Jest and Enzyme testing
BasicPieChart.scss: The SCSS preprocessors
types.ts: A file to hold the types I will be using
Once my data object is ready, the next step is to set up the color scale. I will be using d3.scaleOrdinal(), and for the domain, I can set each name to have its own unique color.

React and D3 pie chart
As always, you can download the complete code of this chapter from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch03
To see this basic pie chart with better integration with React and interactions of resizing and switching metrics check my React + d3 interactive course: https://elielrom.com/BuildSiteCourse.
To create a small donut chart, the process is almost identical. I will use PieArcDatum to draw arcs for the inner and outer circles in order to create a donut. The change is simple. Just update 'innerRadius' property when we create the arc; innerRadius(10).
In the following example, I can change the code and use the props to pass the data from the parent component instead of loading it inside my component. I am also going to write the code so the component can be used to change the data, if needed. Let’s take a look.
First import the library using yarn add d3-shape.
Inside of useEffect, I will be checking the data. This is needed to ensure that I am changing the pie only once new data is being updated. That can happen when you have new data, for instance.
Notice that in my example I am using a reference instead of D3 select. That way I can include my pie as a list item renderer, in case I need to use this component inside a list.

Basic donut pie chart
As for the data, in the previous examples, I showed you how the actual chart component retrieves the data.
This made our code easy to read and loosely coupled, which is a great design to keep the charts simple and the data in one place; however, to prepare you for the next chapter of dealing with a state management, here I extracted the data to the parent component App.tsx.
The reason we would want to extract the data from the chart component is for cases where the data is shared between multiple components. In this case, we want to load the data once and share it with multiple components. A good example is using the same data to draw different charts types.
A scatter chart (aka a scatter plot chart or a scatter graph) represents values with dots. Scatter charts are a great way to observe relationships between variables.

Diamond prices per carat CSV data

Diamond prices per carat cleaned
Our data set is small and has a little footprint, but cleaning up your data and setting up your data set to only consume what you need is a good practice to optimize your data and increase performance. In Chapter 10, I will dive deeper into the best practices of optimizing your charts.
BasicScatterChart.scss: This is just a placeholder for SCSS.
BasicScatterChart.test.tsx: This is the same as BasicPieChart.test.tsx.

React and D3 scatter chart
The chart can show me the price range at a glance, and I can see what to expect in terms of carat size and price for each diamond. If I want to improve the chart, I could insert other fields such as the diamond color’s grade metrics and give these different colors on the chart. I could change the chart per year and filter the data.

Test results for basic chart components
In ‘my d3 and React interactive course you will learn how to include interactive means lines and set resizing, as well as set the component so react control the DOM better, see https://elielrom.com/BuildSiteCourse.
Setting interactive mean lines that move on mouse move events can help the user read the results better and quickly figure price prediction per carat.
The charts we have created so far were relatively simple.
In the donut pie chart, we did check if the data had changed, and we stored the new data set in the function component state, but we haven’t implemented any changes in the chart.
My intention was to just show you how to integrate D3 into a React component that uses TypeScript as the type checker and uses D3 as much as possible.
The last chart in this chapter we will be creating is a basic histogram chart that is going to include input from the user, interactions, and animation. We will use the class component this time, so you can see how to use the hooks built into the React class component to tie together the animations and changes.
A histogram is a bar chart that made out of price and time metrics. Histogram is a common way to show how often values fall into ranges.
The histogram chart groups numeric data into bins. Then bins can be displayed as segmented columns.
We will be building a chart that reviews the price of Ethereum coins over time, so you can see at what price the coin is sold at over time in an easy, intuitive way.
Histogram.tsx: Custom component
Histogram.scss: Style
Histogram.test.tsx: Jest test
For the class signature, I will be using a class pure component (React.PureComponent) versus React.Component since I don’t need to use shouldComponentUpdate event lifecycle.
Now we could also use getDerivedStateFromProps instead of componentDidUpdate, but that method may be called multiple times for a single update, so we would need to place a validator to check whether the state was updated.
componentDidUpdate gets invoked immediately after updating occurs. This method is not called for the initial render.
It’s essential to avoid any side effects, so you should use componentDidUpdate, which executes only once after the component updates.
The heavy lifting is done in the draw method. I could split this code more into an helper class, but the example is not too complex.
The jsx is straightforward.
However, this time I am adding a title and labels using the Material-UI typography component to include our text labels and SVG to hold the <g> elements and a Material-UI slider.
Lastly, I am including the histogram component in App.tsx .
In the pie donut you saw, the data was passed through the props from the parent component.
As I mentioned, we want to extract the data from the chart component for cases where the data is shared between multiple components.
useEffect will be called multiple times, on every rendering, so I want to limit loading the data only once.

Histogram diagram showing prices of Ethereum coin grouped
Looking at the chart, it seems that during 2020 most of the time the price of Ethereum was either about $225 (for about 50 days) or $400 (for about 37 days).
That’s the power of charts. With one look at a chart, I can get the story.
Note I am using charts that are based on investment vehicles in this chapter, but I am not recommending investing in any of the stocks or coins shown in this book.
You can download the complete code for the Histogram component from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch04-05/histogram-d3-ts
This chapter was a continuation of the previous chapter, and in this chapter, I covered how to create some simple charts with React and D3 using TypeScript as a type checker.
Pie chart
Scatter chart
Also, I showed you how to create histogram charts by integrating D3 and React as well as adding more React libraries into the mix.
We used other React libraries such as Material-UI and retrieved the data from a parent component so the data could be shared between multiple components.
In my d3 and React interactive course you can see other ways you can implement all the examples in this chapter with different approaches. The interactive course covers more topics for this section, such as, taking more control over the DOM, interactivity, design, as well as expanding on what’s in this chapter. The course compliment this chapter and book neatly; https://elielrom.com/BuildSiteCourse.
In the next chapter, we will integrate React state management into mix so we can share our data across our app and even with multiple components that do not originate from the same parent component.
In the previous chapter, I showed you how to create simple charts using React function and class components and D3. In the last example, we created a histogram by integrating D3 and React as well as adding other React libraries into the mix such as Material-UI and Jest.
In the histogram, we retrieved the data from the App.tsx parent component so the data could be shared between multiple components.
In this chapter, we will take this chart a step further. We will integrate React state management into the mix so we can share our data across our app and even over multiple components that do not originate from the same parent component. This will be done using state management.
In this chapter, you will learn about the state management architecture introduced by Facebook called Flux, and then you will learn about the new experimental state management architecture from Facebook called Recoil that is poised to take over. In the process, I will show you how to add structure to your chart that can help you build more complex charts, and we will even be integrating a table list component that will use the same data.
One change in the data by itself sounds insignificant and easy enough for your component to implement and manage. So why do we need a state management library to achieve this task?
In layman’s terms, state management helps organize data and user interaction of your app until the user’s session ends. It also helps ensure your code doesn’t get messy as more features are added.
It makes life easier with testing, and it ensures the code is not dependent on a specific development technique and can scale up.
State management is a method of maintaining the state of our app until our user’s session ends.
If you look at the charts we created in the previous chapters, we don’t have a problem and don’t need a design pattern to help us manage our data movement. In fact, implementing an architecture to control our data movement can be seen as overkill for such simple functionality. The state we used is holding the data once it’s received, and it all works just fine.
However, as our code grows and our app becomes larger, with multiple developers and designers, we need some sort of architecture in place to help handle the data movement, as well as enforce best practices to help manage our code so that it doesn’t break with every change.
In fact, Facebook encountered these challenges and looked for ways to solve these problems.
The Facebook team first tried a few tools that already existed. They first implemented the Model-View-Controller (MVC) pattern; however, they found the architecture pattern causing issues as more and more features were added, and a portion of the code was harder to maintain as the code broke constantly.
The React team’s challenges with using the MVC pattern for separating concerns and managing the state for the front end ended up with the creation of Flux.
It’s important to know that Flux state management is being phased out, and the project is in maintenance mode. There are many more sophisticated alternatives available.
Model: The model is the data that is used in the app.
View: The view is the front-end presentation layer.
Controller: This is the glue that binds the model and the view.
The Facebook team explained that when the developers tried using MVC, they experienced issues with the data flow that can cause a loop, which can crash an app as it will become a memory leak (cascading effects by nested updates) and keep re-updating the rendering endlessly.
These challenges were solved by the Facebook team coming with an architecture they called Flux and then more recently with an experimental library called Recoil.
Flux is an application architecture for building user interfaces. See https://facebook.github.io/flux/.
“Flux is the application architecture that Facebook uses for building client-side web applications. It complements React’s composable view components by utilizing a unidirectional data flow. It’s more of a pattern rather than a formal framework.”
From my personal experience, having worked with many MVC-based applications small and large, I have to somewhat disagree with the Facebook team. Some of these projects were very complex enterprise-level applications built on MVC, and by enforcing good habits, MVC-based apps can work seamlessly. With that being said, there is a lot of boilerplate code involved in many of the MVC framework implementations out there, and a code review is often necessary to enforce good habits and to maintain a separation of concerns.
Facebook’s Flux architecture does simplify the process of separating concerns and is a fresh and welcomed alternative to state management, while keeping less boilerplate code and our components loosely coupled. You can learn more about Flux here:
https://github.com/facebook/flux
https://facebook.github.io/flux/
Redux: http://redux.js.org/
MobX: https://mobx.js.org/
Recoil: https://recoiljs.org/
Redux (and the Redux Toolkit) is the most popular state management library at the time of writing. If you want to learn more about Redux, I recommend you purchase my React and Libraries book at https://www.apress.com/gp/book/9781484266953 or read my article at https://medium.com/react-courses/instance-learn-react-redux-4-redux-toolkit-in-minutes-a-2020-reactjs-16-tutorial-9adaec6f2836.
Unlike Redux or the Redux Toolkit, with Recoil there is no need to deal with setting up complex middleware, connecting your components, or using anything else to get the React components to play along nicely with each other.
The Recoil library is still at the experimental stage, but it has already gained some extraordinary popularity, passing even Redux. The Recoil library has close to 10,000 stars on GitHub, passing the Redux Toolkit’s 4,100 stars!
It is my opinion and many others that Recoil will become the standard for state management in React and is a much better investment of your time learning than continuing developing utilizing the Redux Toolkit for the middleware.
However, keep in mind that it is still good to know the Redux Toolkit as you may be involved in a project that uses Redux. Additionally, Recoil is still experimental as of the writing of this book, so it’s not for the faint of heart.
To learn about Recoil, we will be refactoring our Histogram component we created in the previous chapter.
“Recoil works and thinks like React. Add some to your app and get a fast and flexible shared state.”
Recoil was developed and published at a time when there are many state management libraries out there, so you may be asking why we need yet another state management to share our app state. Can sharing state across multiple components and setting up middleware can be done better and easier with Recoil? The quick answer is yes!
If all you need to do is store value globally, any library you choose will work; however, things start to get complicated when you start doing more complex stuff such as asynchronous calls or try to get your client in sync with your server state or reverse user interactions.
Ideally, we want our React components to be as pure as possible, and the data management needs to be done to flow through the React hooks with no side effects. We also want the “real” DOM to be changed as little as possible for performance.
Keeping components loosely coupled is always a good place to be as a developer, so having a library that integrates well with React is a great addition to the React library as it puts React up there with other top JavaScript frameworks such as Angular.
Having a solid-state management library will help React applications serve enterprise-level complex applications as well as handle complex operations on both the front and middle tiers. Recoil simplifies state management, and we only need to create two ingredients: atoms and selectors (https://recoiljs.org/docs/introduction/core-concepts/).
Atoms are objects. They are units of state that components can subscribe to. Recoil lets us create a data-flow graph that flows from these atoms (shared state) to the components.
Selectors are pure functions that allow you to transform the state either synchronously or asynchronously.
Keep in mind that you don’t have to create atoms and selectors. You can just use selectors without any atoms as well as create atoms without selectors.
To show how to get started with Recoil, I will break down the process into two steps.
Step 1: Implementing Recoil
Step 2: Refactoring the view layer
To get started, we would normally first need to install Recoil (yarn add recoil). At the time of writing, Recoil is at version 0.1.2, but that will change by the time you read this chapter. However, our CRA MHL template already includes both Recoil and Redux, so Recoil is already set up without any installation on your part.
Let’s get started.
In our histogram, we create types.ts. The class holds the types we are using in our chart. This type of architecture is great, because it allows us to copy our component and reuse it anywhere we want, keeping our code loosely coupled.
However, Recoil is going to need a definition as well. I could just import the types class, but that would create a composition between our state and our chart.
This would not be ideal if I had multiple charts using the same data, because we would need to import the types.
My decision is to create a model class that I can use to initialize my object as well as have an interface for the price object. This design is not mandatory; it depends on what you need. If you can remove code and everything works and is simple to understand, go ahead and remove code. I am just getting you started here.
As they say, there are many ways to skin a cat. There are pros and cons for each approach; you need to be the judge of whether this works for you.
Now that I have my model object, I can create my Recoil atom.
The key in Recoil should be a unique key. A good practice is to give the key the same name as the filename. Since all the atoms can live in the same directory, src/recoil/atoms/, we can’t have duplicate filenames with the same name, so this will ensure our keys are unique.
The second element of Recoil is a selector. Selectors are pure functions that allow you to transform the state either synchronously or asynchronously. In our case, we can use the same d3.dsv code to retrieve the prices from our CSV file.
Just like the Recoil atom, our selector needs a unique key, and I am making an async call and setting a promise as I don’t want to stop my code.
Once the data is retrieved, I cast it as my type historicalPriceObject[] and use the promise resolve to return the data.
In the previous chapter, we had App.tsx as the parent component that retrieved the data and Histogram.tsx as the chart component.

Histogram widget diagram
This architecture design allows me to be prepared for whatever comes next. For instance, suppose we want to add a list that shows the prices over time or another chart that uses the same data.
Let’s make a histogram with Recoil.
Graph.tsx : Component
Graph.scss: Style
Graph.test.tsx: Jest testing
The widget code will retrieve the data we set up in our Recoil selector and render the chart.
This code is similar to React’s useState, and it’s very intuitive. That’s why Recoil shines.
The data is binding on the Histogram component, and since my two objects Types.Data[] and historicalPriceObject[] are the same, TypeScript won’t complain.
Here I am just using a loading message, but this could be any component, animation, or image.
Our Jest test is a bit different using Recoil. It’s good practice to have full coverage.

Histogram chart with Recoil
In this section of this chapter, I will show you how we can now include another component that can share the same data as our histogram chart.
We will create a table list that displays the days and prices next to our chart.
For the data type, I am creating another types.ts just for my PriceTableList.tsx component.
The PriceTableList.tsx component will be using makeStyle to create our styles for the root container and the table component.
We will be using the TableBody, TableCell, TableContainer, TableRow, and Paper components from Material-UI, so they need to be imported.
To better understand Material-UI tables, take a look at the Material-UI documentation:
https://material-ui.com/components/tables/
That’s it, I am ready to integrate the PriceTableList.tsx component into the parent component HistogramWidget.tsx .

Histogram chart with a list Material-UI component and shared state using Recoil
Check my d3 and React interactive course to see how you can implement this histogram chart using function components and optimize using hooks: https://elielrom.com/BuildSiteCourse.
In this chapter, I talked about the state management architecture introduced by Facebook called Flux and learned about the new experimental state management from Facebook called Recoil.
We took the histogram we developed in the previous chapter and replaced the React state with Recoil state management. Using Recoil state management, we were able to share our data across our app and with multiple components.
This design takes the best of both worlds, consisting of the module libraries from D3 that help us do storytelling with data visualization charts and of a React SPA paradigm with the help of the virtual DOM to make sure the page gets rendered only once a change is made.
We used the Material-UI table list component to create another component and share the data, and we restructured our component into a widget so we can easily integrate the logic for loading multiple components that share data.
Now that you know how to work with D3, charts, and data management to create custom React components. I encourage you to play around with the examples I gave you, plug in data, change the charts, and create new charts. This will help you gain valuable experience.
The rest of the book focuses on working with more complex charts as well as optimization and publishing techniques.
In the next chapter, we will start working with more complex charts. In the upcoming two chapters, the content is dedicated to creating and working with a common type of chart, a world chart.
A world map chart is a great way to show items globally. Integrating D3 with React and TS can create readable code that uses the best of all the tools. In this chapter, I will show you how to create a rotating map and assign dots based on coordinates.
Specifically, in this chapter, I will show you how to work with a world map using React, D3, and TS as type checkers. I will break down the process into steps. In each step, I will be adding more functionality until we have the rotating world map with dots that represent coordinates.
World map atlas: WorldMapAtlas.tsx
Round world map: RoundWorldMap.tsx
Rotating round world map: RotatingRoundWorldMap.tsx
Rotating round world map with coordinates: RotatingRoundWorldMapWithCoordinates.tsx
Refactoring: WorldMap.tsx
The project can be downloaded from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch06/world-map-chart
d3-geo: We will use d3-geo for geographic projections (drawing the map). See https://github.com/d3/d3-geo.
topojson-client: This is a client to manipulate TopoJSON. TopoJSON is the library that provides the map of the world, which I can use to draw the map. See https://github.com/topojson/topojson-client.
geojson: This is a format for encoding geographic data. See https://geojson.org/. TopoJSON files are type “Topology” and follow the TopoJSON specification. GeoJSON will then be used to format the encoding of the geographic data structures. See https://geojson.org/.
react-uuid: Create a random UUID that we will be using for the list key needed when we map the React component. See https://github.com/uuidjs/uuid.
Lastly, download the data of the world atlas. The data is provided from TopoJSON that has prebuilt countries data (https://github.com/topojson/world-atlas). Here is the actual JSON I will be using:
https://d3js.org/world-110m.v1.json
Place the file in the public folder for easy access: /public/data/world-110m.json.
The first map I will be creating is just a flat world atlas type map that will show the world.
Let’s review.
WorldMapAtlas is set as function component. This is a matter of preference, and I could have used a class component.
In terms of the type, I had to figure the type by drilling into the actual geojson library.
Notice that I am using key={`path-${uuid()}`}.
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Keys and refs are added as an attribute to a React.createElement() call. They help React optimize the rendering by recycling all the existing elements in the DOM.
Next, let’s add our WorldMapAtlas component to App.tsx as a child.

Simple world map atlas
As I mentioned, for the projections, I used geoEqualEarth; however, I can change the projection easily to other projections. For instance, if I want to change to geoStereographic, my map will change. See Figure 6-2 .

World atlas map using the geoStereographic projection

World atlas map using geoConicConformal projection
Now we know how to draw a world map atlas. Next we will see how to create a round world map.
To change the map to be round, all I have to do is use the geoOrthographic projection.
To make the round map look better, I am also going to draw a round light gray background using a SVG circle element.

Round world map atlas
Now that we have a round world map atlas, wouldn’t it be neat to add animation and interactions? We can rotate the atlas and add a button to start the animation.
To add animations, we can call JavaScript window requestAnimationFrame API (https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
The requestAnimationFrame method tells the browser that I want to perform an animation, and the browser will call my callback function so that I can update my animation before the next redraw.
Let’s review the code.
Next, I will keep track of the frame using performance.now() (https://developer.mozilla.org/en-US/docs/Web/API/Performance/now). That feature brings a timestamp in the one-millisecond resolution that I can use to figure out the time delta in case I need it.
Time deltas are the differences in times.
I can then use the useEffect hook to tie the animate method.
Now that we have the AnimationFrame hook ready to be used for our animation, I can add my rotating animation. Additionally, I will be adding a user gesture in the form of an icon button from Material-UI to start the animation.

Rotating round world map atlas
One more change we need to make is to place the loading of the map data inside of a statement that checks if the data was loaded.
The reason is that since using the animation hook, the useEffect will get called all the time.
In this section, I will show you how to add coordinate dots to our map.
Copy the RotatingRoundWorldMap.tsx file from the previous example and name it RotatingRoundWorldMapWIthCoordinates.tsx .
Yes, I know it’s a long name, but using Shakespeare’s method names, it’s easy to tell what this component is doing.
Notice that just like the previous step, every time that I am using the map in React I am adding a unique key to each item.

Rotating the round world map atlas with coordinates
Props: Extract the props attributes so the parent component can adjust the attributes and data.
Coordinates: Set the coordinate data as a second data feed in the form of CSV.
Loader: Load the data from the parent component and pass the data to the map chart using asynchronous tasks.
Types: Add the TypeScript types to make the code more readable, avoid errors, and help with testing.
Place the file here for easy access: world-map-chart/public/data/coordinates.csv.
For our refactoring effort, copy the RotatingRoundWorldMapWIthCoordinates.tsx file from the previous example and name it WorldMap.tsx .
Most of the code stays the same.
For the props interface, I will be adding the data feeds and the alignment attributes, so I need to add the props interface and change the function signature.
As you can see, our code in WorldMap.tsx is now cleaner and more readable compared to the RotatingRoundWorldMapWIthCoordinates.tsx file from the previous example.
For the parent component, I will be extracting the data, placing it inside the effect hook, and using the D3 to load both the JSON and the CSV.
Since I want to load both data sets before I draw the map, a good approach is to use the asynchronous calls to both data sets before passing the data to the chart component.
We can use D3’s queue(). See https://github.com/d3/d3-queue. D3’s queue() to do asynchronous tasks. Add these D3 modules and TS types.
Let’s review the code.
The useEffect hook will be doing the heavy lifting. The if statement ensures I am not loading my data multiple times.
Nothing really changes, from the user view perspective, once you check port 3000: http://localhost:3000. However, my code is more organized and easier to read as well as ready to implement state management such as Recoil or Redux since the data is extracted from the actual component and can be shared with multiple components.
In this chapter, we created a world map with the help of D3, TopoJSON, and React. The ability to draw maps as a background and add dots, animations, and interaction can help create a compelling chart that can be used for many things to tell your story.
World map atlas: WorldMapAtlas.tsx
Round world map: RoundWorldMap.tsx
Rotating round world map : RotatingRoundWorldMap.tsx
Rotating round world map with coordinates: RotatingRoundWorldMapWithCoordinates.tsx
Refactoring: WorldMap.tsx
As you can see from this chapter, integrating the world map atlas using D3 with the help of topojson and geojson is straightforward.
Having React involved makes adding animations and interaction intuitive. TS helps ensure we understand what we are doing and that we avoid potential errors, and after doing some refactoring, you can see that our component is not just reusable but ready for state management.
In the next chapter, I will show you how to use the map we created here and implement Recoil state management and a list to create a widget that displays a résumé in an interactive way.
In the previous chapter, we created a world map atlas using React and D3. In this chapter, I will show you how to use the map component we created to share the state across multiple components and interact with the map.
I am often asked by potential clients about my previous work and roles in different companies so they can see if I’m a good fit for their current project. I will be using the map chart to create an interactive résumé to display my previous clients and their locations around the world.

Final results of interactive résumé
This chapter is a continuation of the previous chapter.
Step 1: Setup
Step 2: State management
Step 3: Widget creation
Let’s get started.
In the previous chapter, I worked with coordinates.csv, which included id, latitude, and longitude.
Instead of coordinates.csv, for the client list I will be creating a new CSV file that will include the client’s data feed as CSV and then add additional fields.
For the map data, copy the same world-110m.json file from the previous project and place it here: /public/data/world-110m.json.
As you probably recall, in Chapter 5, I showed you how to work with Recoil and share the state. In this chapter, we will do the same thing and expand the topic by actually sharing the data across different components.
I will be creating a model object to hold our types and then create the Recoil selector.
clientsObject.ts
mapObject.ts
The map object holds the map feature. This is the same code we had in our previous chapter in App.tsx. This time I will move the code out of App.tsx and into its own widget component. This process is not new. We did the same thing in Chapter 5.
Now that we have our model object set, we can create Recoil’s atom and selector. Recoil simplifies state management, so we only need to create two ingredients: atoms and selectors.
For our case, we could use clientAtom.ts and mapAtoms.ts to set the initial state, but we don’t need them. The model we create is enough.
Recoil selectors do not require use to create an atom, and it’s nice to be able to skip a step and write less code. The atoms are great for cases such as when we want to get state updates for multiple components or pass state to the selector. In our case, we don’t need any of these functionalities, so setting the atoms is overkill and can be skipped.
As you probably recall, selectors are pure functions that allow you to transform the state either synchronously or asynchronously.
If you want to create an atom, you can cast the object I am returning as that type. This step is not required, and the code will work fine without doing that, as you will see.

ClientsWidget component and subcomponent high-level wireframe

ClientList generated by CRA MHL template
Next, I will take the WorldMap.tsx component we created in the previous chapter and do a bit of additional refactoring so it fits our needs.
If we look at the code changes from Chapter 6’s WorldMap.tsx compared to the latest WorldMap.tsx in this chapter, we can see there are a few changes.
In the render, the big change is that the coordinate dots, which I set up in the previous chapter, are checked if they’re the selected.
I am using geoEqualEarth, but you can try geoOrthographic or any other D3 geographic projection shape.
Using selectedItem inside the JSX code is crucial because it will ensure the map gets rendered when a new client is selected.
Notice that setSelectedClient is used by ClientList and ClientListDetail to set the selected client. I could have used the Recoil atom state here to avoid prop drilling, however, since it’s not drilling through any components that don’t need the data. Having one method to handle this is fine and a much safer way to help debug and stay out of trouble.
In React everything is a component, and the data is passed from the top down (parent to child) via props. Let’s say you need a prop in a child of a child of a child of a parent component. What do you do? You can pass that prop from one component to another. That technique of deeply nested components using data provided by another component that is much higher in the hierarchy is called prop drilling.
The main disadvantage of prop drilling is that components that should not otherwise be aware of the data become unnecessarily complicated and cumbersome. They are also harder to maintain because now we have to add that in our tests (if we can test) as well as try to figure out the parent component that provided the data.
Let’s review the code.
Let’s review.
The ClientListDetail component includes left and right arrows and methods to handle navigating through the clients using these arrows. Take a look at handleNext and handlePrevious.
The ClientWidget component is the parent component that will fetch the results with the help of Recoil for the map and client list and pass the results down to the subcomponents.
Let’s review.
For the Jest Enzyme test, I am going to make sure the component is mounted.

world-map-widget test results
You can download the project from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch07/world-map-widget
In this chapter, I showed you how to use the world map we created in the previous chapter as a foundation to build a working widget to display a client list using D3, React v17, Material-UI, Recoil, and TypeScript.
Using React with D3 is pure goodness. I was able to create components and let React manage the state and the update of the DOM when needed. It required very little D3 code but is useful as JSX can handle most of it, and our front-end code is readable and managed by the VDOM. Recoil helps keep the state and renders only when needed.
As you can see, using D3 with React can help create neat visualization tools to help showcase information more intuitively.
Lastly, I was able to run format, lint, and test to ensure quality.
My hope is that this chapter serves as an inspiration for you to create your own interactive resume to showcase of work, client list, photo album, or anything you want to highlight.
As you saw in this chapter, using this structure of widget, state management, and components, and setting up the types and model for data, helps create code that is readable and testable. You will be able to easily refactor and add features once a change is needed.
In the next chapter, we will be creating a D3 force chart with the help of React components.
A force-directed graph is a class of algorithms to lay out data in graphs in an attractive way. Force charts can be used for mechanical spring behavior, network visualization, knowledge representation, etc. Using a combination of React and D3 is great since each library can be used for different things. It gives you the best of all worlds. Adding TypeScript as a type checker to the mix helps ensure the types are well defined and helps you avoid potential bugs. Total goodness!
In this chapter, I will show you how to create a basic force chart, namely, a bubble chart with animation that will force each bubble to the center.
Let’s get started.

Final results of a bubble chart
In this section of the chapter, I will show you how to create a basic bubble chart with mechanical spring behavior using D3 and React. For the data feed, I will be using popular opinionated React libraries that are must-haves in every developer’s toolbox. These libraries are covered in more detail in my React and Libraries book: https://www.apress.com/gp/book/9781484266953.
React v17
TypeScript
D3 v6
Other libraries we will be using: Jest and Enzyme, react-uuid
Step 1: Setup
Step 2: Bubble chart creation
Step 3: Redraw
BubbleChart.scss
BubbleChart.test.tsx
BubbleChart.tsx
types.tsx
Feel free to create them with the help of generate-react-cli or on your own.
To hold the component types I will be using in the bubble chart component, I will be creating a TS types file.
In the type file, I will be holding the data feed as well as the specific data that my force chart needs, which is just the size of each bubble.
When it comes to the force animation simulation of the bubbles, I am setting that as a private member that I can access within my component.
My constructor will set up the props and state as well as the method that will create my state variable.
Once the component mounts (componentDidMount), I will animate the bubbles using the D3 force by calling animateBubbles.
The radiusScale function will take d3.scaleSqrt and reduce the scale based on the min and max props we will be providing.
The simulatePosition method is what doing the heavy lifting. The D3 force module does the velocity calculation; see https://github.com/d3/d3-force.
These strength, velocity, and collide settings can be moved as props. Small changes will make big changes in animation and visuals.
To render the bubbles, I could use D3, but React is really much better suited for the job because of the VDOM, and the code will be easier to read.
As in previous chapters, I am giving each group’s SVG a key using the uuid library. You could generate random a key on your own, but that’s my favorite way to generate a key.
To implement this file, I will be including the bubble chart component inside the App.tsx file.
I am setting up the data as an array. The type of the array will be the type I defined in the bubble component and will hold the name of the bubble, the size of the bubble, and the fill color.
This could be easily extracted as a CSV or JSON file, and the data can be shared across multiple components using Recoil if needed. Just as we did in previous chapters, we are actually going to do that in the next section of this chapter when we create the second force graph.
Notice that we have a function that the BubbleChart can call to pass the circle selectedKeyHandler, and we will call an alert.

BubbleChart without animation
Now that we have our bubble chart working, the next step is to add code so we can redraw our bubble chart successfully and provide animations and display them better. We need to be able to redraw in cases where the data changes.
To make these changes, copy the BubbleChart.tsx component, create a new file, and call it BubbleChartWithAnimation.tsx.
To animate and enable the changing of the data, we can tap into the React componentDidUpdate class component lifecycle. Once the component updates based on a data change, we can update the bubble chart with the new set of data. To check whether the data changed, we can use JSON.stringify to create a clone of the data and compare the prevProps data with the new props. If the data changed, set the new forceData as the data as well as animate the bubbles.
I am only showing the changes between BubbleChart.tsx and BubbleChartWithAnimation.tsx.
For the parent component, let’s add a button to update the data. What I can do is to sort my array data randomly so the bubble chart will imitate a change of data. The changes for App.tsx are highlighted.
I am only showing the changes from the previous App.tsx file.
Take a look at the final result in Figure 8-3. Once I click the change data button, the data changes, and the component is animated.

Redrawing bubble chart
You can download the complete project from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch08/bubble-chart
In this chapter, I showed you how to build a simple bubble chart using React, D3, and TypeScript.
We were able to create our component and we used React to help manage the state and update and redraw the DOM when needed.
This architectural design takes the best of all worlds: the module libraries from D3 that lets us do storytelling and the React virtual DOM that makes sure the page gets rendered only once a change is made.
In the next chapter, I will show you how you can create a more complex force charting example of a network force chart, using the same tools I covered in this chapter and the previous chapters.
In this chapter, I will show you how to create a Network graph (force directed graph). We will create a network visualization chart with mechanical spring behavior to represent interview questions you may want to review before your next React job interview. Let’s get started.
A force-directed graph is often used for showing relationships between nodes.

Simple force graph final results
Step 1: Setup
Step 2: Force-chart creation
Step 3: Recoil widget creation
Let’s get started.
For the data feed, I will be using the top React and TypeScript interview questions and answers.
node : These are the nodes we set up in the data feed.
link : These are the links we set up in the data feed.
dataObject : The data object includes both the nodes and the links.
Point : This represents an x and a y.
Datum : This is the internal data for D3.
To represent the elements in the graph, I could draw everything using D3. However, mixing D3 with React is more suitable for the job, since React is more readable and has the built-in logic to update the DOM as well as the style on a refresh only.
Circles.tsx and Circle.tsx : For the circle’s elements
Links.tsx and Link.tsx : For the link (lines between nodes) elements
Labels.tsx and Label.tsx : For the text label of each node
I will be creating a component that will hold all the nodes. Each node will be represented as a circle, but this can be changed to whatever we like.
I will be creating a component that will hold all the nodes. Each node will be represented as a circle, but this can be changed to something else if you like.
For the links (the lines between each node), I follow the same architecture I set up for the nodes. I create a links subcomponent, attach events, and map each item to draw each link.
Notice that since I only need the link data for my props, I am just setting it in the signature instead of creating a props interface.
The link itself calls the link.tsx component for each item mapped to keep the code neat.
For the labels, I can follow the same process similar to how the nodes and links are rendered.
For each label, I need the node data and the dispatcher to indicate the label selected.
This code could be changed to use a context instead of the props drilling I am doing here, but I wanted to leave the code simple. Feel free to refactor it.
The simple force graph as the name suggests will be the main graph component.
In terms of an interface, I will be exposing attributes for the alignment such as the width, height, distance, link strength, and centering.
Let’s review the code.
D3 extends the data provided to it for the force graph, so I need to clone the item since D3 adds an index and I don’t want to modify the original data I am passing from the parent component.
I have the force graph ready. Now the last part is to set up the data and include the force graph component in the App.tsx parent component.
powerChartSelectors
NetworksWidget
App
Now that we have all the pieces, namely, the force graph and a Recoil selector, the last step is to implement them.
Let’s review.
To render the component, I am setting the force graph with the props only once the forceData is set from the Recoil selector component; otherwise, it shows a loading message.
Keep in mind that there are other ways to ensure the content does not bleed. This is just one simple option.
My App.tsx parent component is straightforward; just add the NetworksWidget file.
That’s it! Navigate to port 3000 to check it out. Go ahead and pull the nodes and see how the force simulation pulls them back to the center.
Now, what can I do with this chart?

Flip chart
You can download the project from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch09/force-chart
In this chapter, I showed you how to build a force directed graph chart using React, D3, and TypeScript.
I used Recoil state management to fetch the data, add logic to be able to share the state. I added a widget to include the chart.
This chapter shows you how you can create a more complex chart, using the same tools I covered in the previous chapters.
We let React manage our state and update and redraw the DOM when needed. This gives us the best of all worlds: the module libraries from D3 that let us reuse logic, calculations, force simulations, and even mouse event handling, and React with the help of the virtual DOM to make sure the page gets rendered only once a change is made.
In the next chapter, I will be covering how to integrate popular chart libraries built on top of D3.
As we have covered throughout this book, D3 is the standard when it comes to creating charts.
We have seen how to combine the power of React with D3. This gives an additional benefit because taking advantage of the React VDOM can ensure the DOM is only getting updated when needed. You also get the benefit of other React libraries.
In this chapter, I will be exploring some of the most popular React/D3 libraries. I will first cover the selected criteria I used to test each React D3 library and compare them. In the second part of the chapter, I will show you how to implement each library and give you some of the pros and cons of each.
Keep in mind that I have not worked very long with each library, I am covering so my opinion is limited to what I learned from implementing each example. These libraries are living things, and the information provided here may change, so I recommend checking these libraries out for yourself.
There are gazillions of libraries out there built on top of D3 that include ready-to-use components that have been tested. They are cross-platform and include documentation, community support, examples, mock data, and much more.
With that said, creating a truly innovative visualization chart may be a challenge using a chart “library,” and there’s a good chance that you may find yourself in need of either creating your chart from scratch using D3 or forking the original library you are using to achieve more control over the chart.
However, these third-party libraries do have their purpose and can help create a proof of concept (POC) or expedite development in cases where these vanilla flavors meet your needs.
I want to point out that using these libraries comes with a price. Many libraries may not be set up as modules and can bloat your bundle for a single simple chart. Generic charts can be seen all over the Web as they may be used by hundred or even thousands of apps, and they may have many bugs that would take a long time to solve.
I want to point out that using these D3 React libraries comes with a price. Many libraries are not set up as modules and can bloat your bundle for a single simple chart.
When I say “popular,” I am basing my statement on GitHub engagement and my personal opinion.
Recharts : https://github.com/recharts/recharts (examples: http://recharts.org/en-US/examples)
Visx : https://github.com/airbnb/visx (examples: https://airbnb.io/visx/gallery)
Victory : https://github.com/FormidableLabs/victory (examples: https://formidable.com/open-source/victory/gallery)
Nivo : https://github.com/plouc/nivo (examples: https://nivo.rocks/components)
React-vi : https://github.com/uber/react-vis (examples: https://github.com/uber/react-vis/tree/master/docs/examples/showcases)
Table 10-1 lists my results split into the different criteria.
Table 10-1. Popular React Charts

Let’s review these criteria.
Having TypeScript (TS) as a type checker for me is a must. Even if you don’t use TS now, you might want to in the future.
Many times, all that it takes is a contributor to add the types, or you may need to set the types yourself. If you are on a strict time schedule, you may not have the luxury to do that.
Luckily, all the libraries I have covered include type support. Keep in mind that React-vis includes TS support for the main libraries, but not for many of the modules.
A Library that is based on module approach is better than including the entire library.
In Table 1-1, I used the cost per module (if that was possible). If you need a simple chart that can be created with D3 in a mere few lines of code, it does not make sense to use these libraries, especially since D3 consists of modules as of version D3 version 4 and up.
Rechart does not include modularity, and the entire library had to be included and used. React-vis has a main library that is pretty big in size and other libraries as separate modules.
The rest of the libraries I checked were organized as modules and cost little when I used only one simple chart.
Having mock data makes creating the chart easier instead of having to provide data and setting that up. Having mock data makes using a library much more pleasant out of the gate.
A nice little surprise from Victory is that it includes mock data so no need to bring your own data.
When I talk about simplicity, I mean how long it takes to get going with a ready chart. Most of the chart libraries have good documentation and examples and are easy to get started with.
Visx seems the most complex out of all of them since it is built as small pieces to put together into a composition. This is great in terms of flexibility, but it requires more time to learn and implement.
Having a library that looks nice and is easy to style goes a long way.
It was nice to see a style sheet included in React-vis, and Visx looks great as is, compared with some of the other libraries that look more like wireframes that need to be styled.
Having good documents and examples is crucial and can help you understand how to implement them.
Nivo was a bit of a challenge since I could not get anything to render and display on the screen, just to find out that the wrapper container needs to set the width and height for the container.
Making docs as simple as possible is key. Most libraries were easy to understand with the documents and examples.
Popularity , open issues, and contributors are a big consideration. Rechart takes the lead in terms of popularity.
Visx comes second and gets extra credit as it has the least number of open bugs. React-vis comes last on the list in popularity as well as support.
Recharts
Visx
Victory
Nivo
React-vis
Rechart (https://recharts.org/en-US/) is described as a composable charting library built on React components.
Rechart is the most popular library I have found, and it is built with React and D3. It has 15,800 stars as well as a 1.2K fork on GitHub (https://github.com/recharts/recharts).
Additionally, it has a dedicated website with examples and documentation, and it seems to be well maintained with 177 contributors, but 130 open issues.
The library is based on declarative components (presentational components only), is lightweight with only a few D3 modules included, and supports SVG.
I am going to implement a simple line chart and use SVG as a custom x-axis and y-axis.
For the types I will be setting one file that holds the data object I will set up.
Let’s review.

Rechart line chart component

Rechart library cost
I liked how easy it was to customize my chart using SVG. I was also impressed by the number of charts available, the popularity, and the community engagement. It’s easy to understand the popularity of this library.
Each component is not modular, so I needed to bring in the entire library. With that said, 186.5KB is a not too big price to pay if you need to use multiple charts from Rechart.
Visx (https://airbnb.io/visx/), created by Airbnb, is described as a collection of expressive, low-level visualization primitives for React.
Visx is the second most popular library. The Airbnb team really seemed to make some extra effort with this library, its visual appeal, and its support.
I will be using a bar chart from Visx’s examples.
I used the example from the Visx GitHub location, with a few changes to overcome some of the ESLint errors that were generated instead of just casting them away or ignoring all of them.
The bar keys were based on the array index (which is a big no-no!).
The variable data was used twice.
I removed unused code.
I refactored the name to SimpleBarGraph.
For App.tsx, just include the component: <SimpleBarGraph />.

Visx bar chart component

Visx module size for the bar chart
Overall, I am highly impressed by Visx. It has a small footprint, and as promised, Visx consists of low-level components, which is a great option when you want to get a final product and the Visx functionality is close to what you are looking for. I liked that it has built-in mock data. It’s great to have that so I can focus on the front-end development of the component.
As you can see from the code, the components are broken into small, low-level components that the developer needs to patch together. There is a learning curve in order to use the Visx library. For simple charts, it seems like overkill, and it’s better to just invest your time on mastering D3.
Victory (https://formidable.com/open-source/victory/) is described as React.js components for modular charting and data visualization.
It has almost the same number of stars on GitHub compared to Visx. With that said, there are double the contributors and double the bugs.
I will be implementing a pie chart based on the code at https://formidable.com/open-source/victory/docs/victory-pie.

Victory pie chart component

Victory library cost for the pie chart
Victory is the easiest to implement out of all the libraries I have seen. The examples are easy, there are impressive gallery examples, and there are large followers, fans, and backers.
Victory doesn’t have as many charts as some of the other libraries. Additionally, at the time of writing, there seems to be too many open bugs (https://github.com/FormidableLabs/victory/issues).
Nivo (https://nivo.rocks/) provides a rich set of data viz components built on top of the D3 and Reactjs libraries.
I will be creating a calendar chart (https://nivo.rocks/calendar/).
Let’s review.

Nivo calendar component
The Nivo library is based on modules; however, using one module requires the core library, which costs 241KB, and includes libraries such as React-spring (https://www.npmjs.com/package/react-spring), D3, lodash, and a few Nivo libraries.
I am impressed by the selection of unique charts that Nivo offers; they are nice looking and easy to implement. The library has a server-side rendering (SSR) API, which is great when working with large data sets.
The examples are not as straightforward as they can be; when I tried to use some of the examples provided by the docs, I could not get them to render, so I had to figure out that the wrapper container needs to have a width and height set; otherwise, nothing will show. It would have been easier if they has set some default values to get something to render and allow us to override the default settings.
React-vis (https://uber.github.io/react-vis/), created by Uber, is described as a composable charting library.
It’s the least popular library on the list. There are 116 contributors and 277 open bugs.

React-vis line chart component

React-vis
React-vis was easy to implement, and it includes a large selection of simple and custom charts. Additionally, I really liked how React-vis comes with a built-in CSS file to help style the components.
The library seems inconsistent, large in size, with too many open bugs, and the library could use an architectural refactoring.
You can download the project from here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch10/react-chart-libraries
In this chapter, I covered some of the most popular React D3 libraries. In the first section of this chapter, I compared the different libraries using specific criteria.
In the second part of the chapter, I showed you how to set up, implement, and use each library and included the cost of each library and the pros and cons.
As you have seen, using a ready-made component built on D3 with the use of React is a no-brainer. We get hours of work done for us effortlessly; many of the charts are open source and cross-platform; and they come with mock data, documentation, examples, and even community support.
With that said, there are too many open bugs in all these libraries, and the release bundle increases significantly in many of the libraries I used. If all you need is a simple chart, they seem like overkill. Continuing to invest time in D3 appears to be the better option.
As you have seen, each library includes different sets of charts and has pros and cons.
Rechart is the most popular with the largest number of contributors.
Visx is an impressive library with the unique charts being offered, the support, and the level of organization. It does require effort to understand and work with all the module pieces.
Victory is great because it is simple to implement and has many different charts to offer.
What it boils down to is finding the chart you are looking for. If you find one that is close to what you need, then it is worth it to start from zero and implement it using D3.
With that said, D3 also has a learning curve. I think that knowing these libraries and keeping them in mind is useful; however, if you are serious about charts, there is no escaping learning D3. Once you understand D3, that knowledge will help you to customize these ready-made components. Plus, you can always fork the open source components if they don’t have what you need.
Semiotic : https://github.com/nteract/semiotic ( examples: https://semiotic.nteract.io/examples)
react-d3-components: https://github.com/codesuki/react-d3-components (examples: https://github.com/codesuki/react-d3-components#examples)
Keep these others in mind, and even if you don’t use them, these libraries can be used as inspiration for your customized chart.
Many times data visualization requires lots of resources to run. For instance, consider the features that a common chart includes: animations, a live data feed updating at runtime, a chart with thousands of records or a few charts placed on a single page, and so on.
These requirements can cause a sluggish experience, especially when the user is using a less capable device such as an old mobile device or a computer with low memory or a slow network connection.
In this chapter, I will show you some performance tips you can implement to provide a better user experience.
Data loading
Installing modules instead of global imports
Server-side rendering
Tree shaking
Updating the DOM only when needed
Using CSV over JSON
Optimizing CRA with prerendering, prefetching, and precaching
Memorizing functions with useCallback
The complete chapter code can be found here:
https://github.com/Apress/integrating-d3.js-with-react/tree/main/ch11/knick-knacks
The core of working with charts is the data. Optimizing the data being sent across the wire can make a significant impact on the time it takes to load the chart.
You should only transmit the metrics you need instead of loading the entire data set. For instance, in our previous chapter, we drew a calendar chart with Nivo using a data set of calendar.json.
That data set included data from 2018; however, the chart I used was set to display the data from 2019–2021, so all that data from 2018 was not needed in our app, and it would have slowed down the user experience unnecessarily.
Similarly, when we created the network force chart in the previous chapter, we used the power_network.json file, which included the fillColor field with the color of the node.
That was great that we could control the color of each node; however, that is not needed, because we can change that to a type and create an enumeration class that points to the type that we can then use later in the code.
The general rule to reduce overhead is to avoid duplications in the data and in the code.
Similarly, if you send data over the wire, there are many ways to decrease the size and send only what you need. A good example is GraphQL (https://graphql.org/), which gives clients the power to ask for exactly what is needed and nothing more.
To measure how long it takes to make these service calls, you can use the browser tools or other third-party tools.

Chrome network response timing breakdown for calendar.json
Make as few requests as possible: Keeping a low number of requests is more important than the number of kilobytes transferred, and that goes for any resources. That was proven by performance tests.
HTTP 3 over HTTP2 and avoid HTTP: HTTP 3 is the best option, and it’s about 100 time more common. Why? It’s because most sites link to the same resources such as analytics.js and fbevents.js.
Async over blocking requests: Use async and avoid blocking requests as much as possible.
With D3 (version 4 and up) as well as many other libraries, it is possible to import certain modules instead of the entire library. Doing that can reduce the bundle size needed to run the app significantly.

CRA MHL template initial bundle size
As you can see, the parsed tree map size of CRA MHL is 214KB. That includes React and React DOM v17 (129.17KB) as well as Recoil (54KB).
Stat size: This is the size of the input after webpack bundling but before optimizations (such as minification).
Parsed size: This is the size of the file on disk after optimizations. It is the effective size of the JavaScript code parsed by the client browser.
gzip size : This is the size of the file after gzip is usually transmitted over the network. Keep in mind that gzip will need to unzip once it reaches the client (browser).
If we create the same code, we can just change it to first use the global D3 library and then use the d3-selection module we are using. The code is almost identical; however, the footprint changes.

D3 global library parsed size
As you can see, the D3 library is 37.57KB parsed.
Run the analyzer again to check the bundle size. See Figure 11-4.

D3 module library parsed size
The CRA (SPA) paradigm is great for certain cases because you don’t get any page refreshes, so the experience feels like you are inside a mobile app.
The pages are meant to be rendered on the client side. In addition to SPA, there is another option that I mentioned before in the book: server-side rendering (SSR).
CRA doesn’t support SSR out of the box. However, there are ways to configure the routing, etc., and to get CRA to work as SSR, but that may involve ejecting and maintaining the configuration on your own and may not be worth the effort.
Ejecting means you’re taking on the responsibility of updating the configuration build code that you may not fully understand. If the build breaks, CRA may not be able to support the custom configuration you set up, and updating the build files may break.
If you’re building something that needs SSR to increase performance, it’s better to just work with a different React library that is already configured out of the box with SSR such as the Next.js framework, Razzle, or Gatsby (which include a prerender website in HTML at build time).
If you want to do server rendering with React and Node.js, check out Next.js, Razzle, or Gatsby.
Tree shaking (https://webpack.js.org/guides/tree-shaking/) is a term used in JavaScript to mean removing dead code.
Never executed code : The code is never executed during runtime.
The result never used : The code is executed, but the result is never used.
In our current project configuration, we have Recoil state management, but we are not using the Recoil feature for anything.

Recoil library size footprint
Having imports for libraries we are not using increases the size of our code (JS bundles). These imports should be removed.
When working with D3 and React, as we have seen, the biggest advantage is that we can let React control the DOM. React VDOM needs to update only once a change is made. We need to ensure we are rerendering only when a change is needed.
The D3 code is considered a side effect because it adds content to the DOM outside of React’s VDOM mechanism. Because of that, we want to let the VDOM know when to redraw.
In a function component, the useEffect hook is used for any side effects, and after the component is unmounted, any events that are not React-based need to be cleaned manually to ensure there will be no memory leaks.
But that’s not enough. The other concern we may have is to ensure our chart is updated only when needed, instead of on every component update.

HelloD3Data.tsx component
What happens here is that React calls useEffect on every update, and since D3 draws the DOM, it causes a redraw of the same code.
What we need to do is check for a data update.
Check D3 data : Check the data inside D3 elements.
Clone : Clone the data locally.
Create React class component : React class components already have logic built in that passes previous values.
This approach is great, but it is less desirable than checking the data in D3, since we now have the same data being stored in memory or a reference three times (props, state, and HTML element).
With that said, cloning data is a sometimes necessary step, since the D3 logic changes data inside an object and React props would not tolerate that. TypeScript will actually spit out an error message: “TypeError: Cannot add property index, the object is not extensible.” As you remember, we did that when we created the bubble and power charts.
As you can see, all the options I have shown you (Check d3 data, clone, and React Class component) are valid, and they allow us to control that the D3 update takes place only when the data is changed to avoid unnecessarily updating the DOM constantly.
As you can see and I mentioned earlier in the book, I use React.PureComponent over React.Component when possible, since it gives a performance boost in some cases in exchange for losing the shouldComponentUpdate lifecycle event. Both React.PureComponent and React.memo() are preferred over React.Component.
When creating D3 charts, it’s common to use CSV and JSON for the data feed, and indeed we have used CSV and JSON in many of the examples in the book.
CSV uses less bandwidth : CSV uses the character separator, and JSON needs more characters just for the syntax format.
CSV processes data faster : The CSV character separator is quicker to split, and in JSON the syntax needs to be interpreted.
The CRA (SPA) paradigm is great for certain cases, because you don’t get a page refresh, and the experience feels like you are inside a mobile app.
The pages are meant to be rendered on the client side. CRA doesn’t support server-side rendering out of the gate.
However, there are ways to configure the routing, etc., and get CRA to work as SSR, but that may involve ejecting and maintaining the configuration on your own and may not be worth the effort.
If you’re building something that needs SSR, it’s better to just work with a different React library that is already configured out of the box with SSR such as the Next.js framework, Razzle, or Gatsby.
If you want to do server rendering with React and Node.js, check out Next.js, Razzle, or Gatsby.
CRA is agnostic on the back end and produces only static HTML/JS/CSS bundles. With that being said, with CRA we can do prerendering, which is the closest you can get to SSR at this time. See the CRA documentation at https://create-react-app.dev/docs/pre-rendering-into-static-html-files/.
react-snap
react-snapshot
Webpack Static Site Generator Plugin
I recommend React-snap (https://github.com/stereobooster/react-snap) as it is more popular on GitHub and works seamlessly with CRA.
React-snap uses Puppeteer to create prerendered HTML files of different routes in your application automatically.
The biggest benefit is that once we use React-snap, the app doesn’t care if the JS bundle is successfully loaded or not because each page we set would be on its own.
Keep in mind that for each page to load on its own, some bundle may have redundant code, so it does come with a price.
Step 3: The static HTML rendered almost immediately; it is unstyled by default and can cause an issue of showing a “flash of unstyled content” (FOUC). This can be especially noticeable if you are using a CSS-in-JS library to generate selectors since the JavaScript bundle will have to finish executing before any styles can be set.
React-snap uses another third-party library under the hood called minimalcss (https://github.com/peterbe/minimalcss) to extract any critical CSS for different routes.

Rectangle folder created inside build folder
You might have used higher-order components (HOCs) in React to enhance a component capability (https://reactjs.org/docs/higher-order-components.html). We can take a similar approach when it comes to our JS bundle.
We want to first load the page and then retrieve the JS bundle, so we get to display the page ASAP.

Hierarchy not set for JS bundle
We want to move these chunk bundles to the bottom. To do that, we can use Quicklink (https://github.com/GoogleChromeLabs/quicklink).
Running prerender and serving static pages is not necessarily always the best approach; it can actually create an undesired experience for your users as each page will load and the component load will be distributed across pages. For light apps, it may be better to wait half a second for all the content to load, with no more wait time, than waiting a bit on each page load. You need to test and see for yourself, but be aware of this feature.
Step 5: To spin off a production build locally, run the CRA template and then and then the run script (yarn build:serve). It’s using the serve library, so you don’t even need to install or configure package.json if you are using the CRA MHL template.

HOC worked bundle chunks are at the bottom
I want to point out that another big reason to use prerender is the need for static pages beyond optimizing with search engine optimization (SEO). If you prerendering pages and want to generate a different title, description, metadata, etc., for each page due to SEO reasons, or need to share individual pages via social media, check out react-helmet that can help to set a unique header for each React page component.
Being able to go offline is a core functionality of a progressive web application (PWA). We can do that with a serviceWorker.
CRA includes a “workbox for production” build out of the box (https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin).
Now when you build again ($yarn build), a new file appears: build/precache-manifest.[string].js.

The runtime-main bundle file was added to our static folder

Precaching ServiceWorker shows up in the Chrome DevTools Network tab
Go ahead, turn off your network connection, or on the Chrome DevTools Network tab, check the Offline checkbox.
You can now simulate an offline experience. Refresh the app; it still works as if you are online!
The workbox default precaching strategy for CRA is CacheFirst. Static assets are retrieved from the service worker cache mechanism, and on fail, a network request is made.
Workbox supports different strategies such as CacheOnly, NetworkFirst, etc., but CRA may need to be ejected to use a different strategy than the default.
Read more about this feature at https://create-react-app.dev/docs/making-a-progressive-web-app/.
However, that code is problematic because it can cause an infinite loop! useCallback() can help prevent this.
The memoizedDrawCallback function will not get rebuilt on every render DOM cycle update, so we have broken out of a potential infinite loop! In my d3 and React interactive course you can see how to implement many of the examples in this chapter with the memorizedDrawCallback approach. https://elielrom.com/BuildSiteCourse.
Applying the methods in this chapter and measuring the results can help reduce the application footprint and the load time in precious seconds.
In the next and last chapter, I will be covering publishing your React D3 chart as both a SPA and with SSR.
Congratulations for making it to the last chapter in the book. You should be proud of your commitment, and I am pleased you have reached this chapter. Now that we have some charts ready, it is time to publish the React and D3 code.
There are many factors to consider, and many options are available. As a team lead, startup advisor, CTO, or any technology professional, you may need to make a decision about which tool to use. So, which should you pick?
In this chapter, you will be learning about some of the best options you can select for your React starter project. Additionally, I will walk you through the process of creating one example of a SPA React app as well as an SSR React app and publishing the code.
Selecting your startup project
Creating and publishing an SSR app with Next.js
Creating and publishing an SPA with CRA
Helpful debug profile tools
Let’s get started.
In many cases, selecting a technology stack for the development environment has already been done for you. However, if you need to recommend a technology stack (even if you don’t need to publish your app yet), it’s good practice to create a published build.
Creating a published build is important because it gives you a more realistic build than with the libraries that are already optimized and ready for deployment.
While you work on your project. Changes in the code could be significant, and it’s important to constantly create published builds and not to wait for the last minute at the end of your sprint to find out that the build is broken or not working as expected.
I am a true believer that you should be publishing fast and publishing often, even twice a day.
When it comes to deciding what tool to pick, there are many paid and free solutions and options out there in terms of publishing your work that it can become overwhelming.
Additionally, you have options for using React as a SPA than choose SSR, with fully configured servers such as Ubuntu or Windows, or as serverless with no configuration solutions.
What it boils down to is what other technologies you need to integrate with, usage, costs, maintenance, langagues be deployed, your personal preference, team experience, community support, and many other facts.
To try to give you a way to look at it, I created the high-level activity diagram in Figure 12-1. This diagram can help you decide how to plan your publishing options from start to finish. Note that this activity diagram is simplified and doesn’t go into all the details that should be considered.

Activity diagram for selecting a startup React project and publishing
The first step that I recommend taking once you have decided on React as your web technology is deciding if you want your app as a single-page application (SPA) or to have server-side rendering (SSR) .
Using dynamic content instead of simple static pages results in improving user experience and increasing engagement. For instance, consider these features that your code may include: interactions, animations, a live data feed updating at runtime, dealing with thousands of records, the number of components placed on a single page, and so on.
When using a SPA, the rendering is done on the client side, and external resource usage is limited. Server-side rendering is the ability of an app to display content on the server instead of rendering it in the browser like in a single-page application.
There are times where using SSR is preferred over SPA. There are a lot of considerations that go into when and why to use SSR over SPA, and it goes back to the team’s experience, technology stack, performance, code size, and many other considerations.
SSR was built to support SEO out of the gate and serve static pages; however, SPAs can also be set up with additional libraries so the content is cached and even works offline, as you saw in the previous chapter. This can be done by optimizing the SPA with techniques such as useCallback, prerendering, prefetching, and precaching, as you saw in the previous chapter.
The user machine less taxed
The ability to share code with the back-end Node.js
SSRs increase the complexity of your app.
SSRs degrade the response time if the server is busy.
You may already be using SSR or SPA, so how can I convert between the two?
Even if you picked an SPA and need to convert the project to an SPA or vice versa, React component’s first paradigm is built for dragging and dropping components if they were built right, so you should be able set up your project by moving the components over.
Once you decide on SSR and SPA, you need to decide on the startup library you want to use. Using a starter project is great because you don’t need to configure the project, and you can get started right away. You saw how easy we were able to start projects quickly with CRA MHL during our book examples.
However, since the templates are vanilla flavor, it’s one size fits all, and you need to put effort into adding and/or removing whatever React-based libraries you use or need.
CRA (https://github.com/facebook/create-react-app) is Facebook’s recommended starter project, and with 86,000 likes on GitHub and Facebook’s seal of approval, you know you are in good hands. However, that starter project is based on SPA technology.
Turning that project into a pure SSR app is possible, but it will require ejecting (you will need to manage the configurations yourself) and setting it up on your own. I would not recommend that approach unless you are very savvy with your knowledge of the moving pieces.
If you need an SPA, I would go with Next.js (https://nextjs.org/). Next.js is the most popular SSR-based React starter project (with 63,000 stars on GitHub), at the time of writing, and is being used by many successful companies such as Netflix, GitHub, Hulu, and Uber.
Gatsby: This offers serverless rendering used by companies such as PayPal, Spotify, IBM, and more. See https://www.gatsbyjs.com/. (This is very close in popularity to Next.js.)
React Boilerplate: This focuses on offline mode and scalability (https://github.com/react-boilerplate/react-boilerplate).
React Slingshot: This is built with some opinionated libraries such as Redux, Babel, hot reloading, and more (https://github.com/coryhouse/react-slingshot).
Razzle: This is SSR based, with no configuration (https://github.com/jaredpalmer/razzle).
Additionally, you can start your project from scratch and install the libraries you need on your own as well as manage the configurations on your own. It does require more effort to set up, but you can ensure your project fits your needs like a glove.
There are so many solutions and options out there in terms of publishing your work that it can become overwhelming if you need to pick the technology yourself.
GitHub pages
Vercel
Firebase
Netlify
Heroku
And many others
Amazon AWS (see Lambda for serverless)
Azura (see Azure Functions for serverless)
Alibaba cloud (see Function Compute for serverless)
And many others
Keep in mind that today many solutions are free to get started with based on using a trial, based on your early usage, or both; however, once you start using the resources, the bills start coming in.
You should estimate your resource usage for when you scale up or the trial period ends, so make sure to read the fine print and read it often. Also, set alerts in the billing section (if this exists). I am not in any way recommending any tool here; do your own research before picking a solution.
How can companies afford to give services for free? Most cloud services realize that collecting cents turns into millions, and usually the needs grow beyond the minimum usage. The effort of moving to a different solution is hard if the setup process was not documented well.
I highly recommend you document how you set up your project to avoid being married to a solution. Prices and terms change often.
In the next section of this chapter I will show you how to set up a starter project with Next.js and publish the work.
So far in the book, we have used CRA for our projects. In this section, we will create a starter project with Next.js. The only prerequisite is having Node.js and Yarn installed, which we do.
When we run these libraries, notice that the tsconfig.json file will be added to your project automatically.

My custom React + D3 component on Next.js starter project
Now that we have our app ready, one approach is to publish that app on an Express server.
Next, let’s create an express server file that can serve our app. On the code level, I am allowing you to pass the port that will be used or set it as port 9000 (feel free to change to port 3000 or whatever you prefer).
We have seen our SSR React app running with the help of internal Next.js scripts as well as with my custom Node.js Express server script. Getting from here to production with the serverless option that doesn’t require configurations is easy once you understand the process and do it a couple of times to practice.
As I mentioned, there are plenty of solutions out in the wild, free and paid.
Heroku is one of them. First, you would need to create an account: https://signup.heroku.com/.
You also need the Heroku CLI.
For Windows users, download the installer.
https://devcenter.heroku.com/articles/heroku-cli
Before we publish, there is one more step. We need to set our run script on pacakge.json with a start run command that points to the server file we created. That start command will be used by Heroku automatically.
As you can see, creating a starter project with Next.js, running a published version, and publishing your code was straightforward with little work on our end and is similar to what we have done with CRA.
Next , use the same Rectangle.tsx component we created previously and place it here: src/components/Rectangle/Rectangle.tsx.
The easiest way to publish CRA code would be to use CRA serve and let it handle the rest.
Keep in mind that the same script works in Next.js as well. That will open your browser with a published script.

Running published build with serve
To shut down the server, press Command+C on a Mac (or Control+C on PC) to close the server.
Next, we can set up CRA with Express in the same manner that we set up Next.js.
The command should open a browser and allow you to log in and accept.

Project published on Heroku
CRA has a publishing options page at https://create-react-app.dev/docs/deployment/.
Now that you have published your app, you may find a bug or two and need to fix your app. Debugging is a common practice for detecting and removing errors (also called bugs) in your code that can cause undesired behavior.
When you work with a React app, there are some specific useful tools you can use to debug and profile your app when you run into problems. Having the right tools for the job and knowing how to use them can remove pain points and expedite the process.
React is based on JavaScript, and all the same tools that work for any JS-based app work on React. Techniques such as inspecting DOM elements, IDE debugging, and setting up alerts and console messages are all valid.
I am not going to show the simple and common ways to debug and profile your app as this book assumes you have some working knowledge of React, HTML, and JavaScript; however, feel free to check out my other React book:
https://www.apress.com/gp/book/9781484266953
These resources highlight a few methods that you may not be unaware of.
In this last section of the chapter, I want to point out additional tools that can help you get the job done once you publish your code.
Debug and profile with Chrome DevTools
React Chrome DevTools extension
React Profiler API
Chrome DevTools extensions is the standard and one of the most common tools used to debug and profile an app. If you need to test an app in other browsers, keep in mind they also provide development tools similar to Chrome.
The React team, as well as the React community, built a Chrome DevTools extension that can help.
React Developer Tools: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi
Realize for React: https://chrome.google.com/webstore/detail/realize-for-react/llondniabnmnappjekpflmgcikaiilmh
Recoil: https://chrome.google.com/webstore/detail/recoil-dev-tools/dhjcdlmklldodggmleehadpjephfgflc
React Developer Tools lets you inspect React component hierarchies in the Chrome Developer Tools. We get two new tabs in your Chrome DevTools: ⚛ Components and ⚛ Profiler.
To test the tool, I am using my site and navigating to https://elielrom.com/Books.

React developer tools—components window
The second tab is for Profiler, where we can record a production profiling build.
The React Developer Tools Chrome DevTools extension has two tabs: Components and Profiler. The Profiler tab gives insight into what is called Flamegraph.

Flamegraph results for my development build

Ranked results for my production build
You can also opt in to your production build to get profiling working. Keep in mind that setting up profiling on a production build does come with a small overhead.

Realize for React Chrome DevTools on https://EliElrom.com
This holistic overview is breaking down the AppRouter.tsx file on my personal site neatly.

Recoil Chrome DevTools on https://EliElrom.com
The React Profiler API (https://reactjs.org/docs/profiler.html) includes a <Profiler/> component that helps customize the metrics from the source code to measure the component’s lifecycle time.

Profiler API results on CRA-MHL template development build
In this example, I am logging everything, but we can create a script that will filter results and handle them in different ways.
As you have seen, you have plenty of options when it comes to selecting your startup project and publishing your React app. First, decide whether you want to use an SPA or SSR, next select the startup project, and then select server or serverless. What it boils down to is what other technologies you need to integrate your React project with, usages, costs, maintenance, languages, your personal and team experience, and many other facts.
In the last part of this chapter, I showed you some helpful debugging and profiling tools that can help you in your development journey. I want to thank you for purchasing this book, and congratulations for completing it.
Check my d3 and React interactive course to see other ways you can implement all the examples in this book with different approaches plus insights and more explanation.
The interactive course is packed with material that covers more topics, such as, taking more control over the DOM, color spaces, interactivity, design, as well as expanding on what's in this book. The interactive course compliment this book and can help you master React and D3; https://elielrom.com/BuildSiteCourse.
Send me social media post of you and the book and receive a discount code for the interactive course.