Data Visualization for React Developers The Three Exceptions
Transcript from the "The Three Exceptions" Lesson
>> Shirley Wu: I think using React to render, and D3 to calculate, is as simple as that, as simple as those exercises. But what I do want to talk about, and this is kind of the parts where React and D3 don't play so nicely together. So for all of the things over here, in the first and second column, these play really, really well with React.
[00:00:22] Because it's essentially D3 doing the calculation and returning a data object back to you. But the things that I've highlighted in here, these four functions, they need access to the DOM to do their job. And so if you can imagine, React already wants control of the whole DOM so that it can do its virtual DOM thing, and it can manage all of the updates and changes to the DOM.
[00:00:48] And so when people say that D3 and React don't play nicely together, they're talking about specifically these few functionality, and actually also, the third column. So the third column and these four, because these are the D3 functionality that needs direct access to the DOM. We're going to actually go through three out of four of these, and I'll give you an example of how these work.
[00:01:16] But for these specific four functions where D3 needs to do the rendering to the DOM, the way that I usually do it is, I instantiate the D3 function in componentDidMount. I create a group container in render, an SVG group container. And then I place the D3 code in componentDidMount and/or componentDidUpdate.
[00:01:43] And the thing that I want to stress over, and over, and over again is that if you do decide that you need to use one of these four functions with your React app. The thing I must stress over and over again is never, ever, ever, ever let D3 and React manage the same parts of the DOM, ever.
[00:02:04] Please, or else you're going to get hideous bugs. I still remember four years ago when I was doing D3 and React together, for the first time ever. And I sat there for a whole afternoon trying to debug this super weird bug that I just couldn't figure out. And it turned out it was because D3 was updating this one attribute that React also was trying to update.
[00:02:28] And then React was like, no, and D3 was like, what? And so, [LAUGH] it was not fun. It was traumatic enough that I still remember it four years later. So please never, ever let D3 and React manage the same parts. And that's why when you need D3 to render something, you create a group container, you give it a ref, you pass it to D3.
[00:02:53] D3 does everything within that group container, and React doesn't need to know about it. So this is the section that's exceptions, please proceed with caution, and please only do it if it's absolutely necessary.