React state is component-owned data that can trigger the component to render again when updated. Functional components commonly store state with useState, receiving a value and its setter as a pair. section 8.3
Use state to represent values that change during a visualization:
- Store loading status, initially true, and render either a loading message or the charts. section 8.3
- Store fetched data, initially as an empty array, then pass the updated data to a chart component. section 8.3
- Store the active filter and update it when a button reports a different selection. section 8.7
Loading chart data
Declare loading and data with useState. Fetch data inside useEffect, call setData when the Promise resolves, then call setLoading(false) so Charts receives the available data instead of the loading message. section 8.3
Listing 8.2 Loading data into App.js
import { useState, useEffect } from 'react'; #1
import * as d3 from 'd3';
import Charts from './Charts/Charts';
const App = () => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]); #2
useEffect(() => {
const dataURL = "https://d3js-in-action-third-edition.github.io/
hosted-data/apis/front_end_frameworks.json";
d3.json(dataURL).then(data => { #3
setData(data);
setLoading(false);
});
}, []); #4
return (
<div className="container">
{loading && <div className="loading">Loading...</div>}
{!loading && <Charts data={data} />} #5
</div>
);
};
export default App;
Inspect the complete App component showing initial state, asynchronous updates, conditional rendering, and data passed through props. section 8.3
const filterSelectionHandler = (id) => {
if (activeFilter !== id) {
setActiveFilter(id);
}
};
Inspect a guarded state update that changes the active filter only when the clicked identifier differs from the current value. section 8.7






































