useEffect is a React Hook for running work after rendering. It connects React components to asynchronous data loading and D3 DOM operations without placing those operations directly in the returned markup. section 8.3 section 8.5.1
Use the dependency array to control when the effect runs:
- Pass an empty array to run the effect once after mounting, as with an initial REST request. section 8.3
- List changing props or values as dependencies when the effect must rerun; curve animation depends on data and the line generator. section 8.7
- Return cleanup logic when asynchronous work might finish after unmounting, preventing updates from an obsolete component. section 8.3
- Combine useEffect with useRef when D3 needs to select and control a rendered SVG element. section 8.5.1
Load data before displaying charts
Initialize loading state as true and data as an empty array. Inside useEffect, call d3.json(), update both states when the Promise resolves, and render Charts only after loading becomes false. The empty dependency array makes this initial request run once.
Listing 8.19 Applying a smooth transition to the curves (Curve.js)
import { useRef, useEffect } from "react"; #1
import * as d3 from "d3";
const Curve = props => {
const lineGenerator = d3.line()
.x(d => props.xScale(d[props.xAccessor]))
.y(d => props.yScale(d[props.yAccessor]))
.defined(d => d[props.yAccessor] !== null)
.curve(d3.curveMonotoneX);
const pathRef = useRef(); #2
useEffect(() => { #3
const path = pathRef.current;
d3.select(path)
.transition()
.duration(400)
.ease(d3.easeCubicOut)
.attr("d", lineGenerator(props.data));
}, [props.data, lineGenerator]); #4
return (
<path
ref={pathRef} #5
fill="none"
stroke={props.stroke}
strokeWidth={props.strokeWidth}
/>
);
};
export default Curve;
Inspect a complete hybrid React-D3 effect that selects an SVG path, transitions its d attribute, and reruns when its data dependencies change. section 8.7



