React Data Visualization: Matching Chart Choices to How Fast Your Data Moves

2026-11-30来源 dev.toEnglish
React Data Visualization: Matching Chart Choices to How Fast Your Data Moves

Banner: React Data Visualization, matching chart choices to how fast your data moves. A grid of small grey dashboard tiles on the left and one blue live waveform on the right.

TL;DR: React charts slow down in two different ways that need different fixes. A dashboard slows because many charts share one page, so you aggregate on the server, keep props stable, and share rendering resources. A live view slows because data keeps arriving, so you append to the chart's own data series, cap its size, and clean up on unmount. Three questions about freshness, update rate, and aggregated versus raw data tell you which one each panel is.

Pick any "best React chart library" list and you will find the same ranking logic: a feature count, a speed number from a demo, maybe a bundle size. None of that tells you whether a library suits the screen you are building, because a screen with forty small charts and a screen with one fast-moving chart stress completely different parts of the stack.

This post goes at it from the data side. It gives you three questions that sort any panel into a profile, then the rendering and data-flow choice that fits each one, with code where the choice is not obvious. By the end you will know which profile your busiest panel falls into, what to build for it, and which measurements to run yourself instead of trusting a headline figure.

Three Questions That Sort Any Panel Into a Chart Choice

Suppose we have a wind farm operations team with two screens. The fleet overview shows 40 turbines as small tiles, each with a 10-minute average power trend. The diagnostic view streams the raw vibration sensor of one selected turbine at 1,000 readings per second.

Both screens are "React data visualization," and they have almost nothing in common. Three questions explain why:

  • How fresh does the data have to be? A fleet overview that is a minute old is fine. A vibration trace that is a minute old is useless.
  • How often does it update? Refreshing on a schedule or a filter change is occasional work. A feed is work that never stops while the page is open.
  • Does the browser receive aggregated or raw data? Aggregated data is summaries computed ahead of time, such as one average per 10 minutes. Raw data is every sample as recorded.

Answer those for each panel and the profile follows. The overview is fresh to the minute, refreshed rarely, and aggregated. The diagnostic view is fresh to the second, updated continuously, and raw. A third kind exists too: a dashboard that contains one live panel. The sections below take each profile in turn.

Infographic: two wind farm screens side by side. The fleet overview is 40 small tiles refreshed rarely. The diagnostic view is one chart fed 1,000 readings a second without a pause.

Three Ways a React Chart Puts Pixels on the Screen

React models a screen as components that re-render when state or props change. A chart library then maps each data point to a position and draws it. The drawing approach shapes the profiles below, so here are the three in common use.

  • SVG. Every part of the chart becomes a DOM element. Recharts works this way and models each piece, such as an axis or a line, as its own React component, so node count grows with the marks drawn.
  • Canvas. The library paints into one bitmap, which puts less load on the DOM tree than SVG. Chart.js works this way.
  • GPU. The library draws through WebGL or WebGPU. SciChart.js v6 combines a WebAssembly engine with WebGPU and WebGL rendering, and it keeps its own data containers, so chart data does not have to live in React state at all.

React draws a line between these worlds. Effects exist to synchronize components with an external system such as a non-React widget, and a canvas or GPU chart is exactly that: React owns the container element, and the library owns every pixel inside it.

Components should also survive being remounted, which applies directly to live charts because effects run twice in development.

Profile One: Dozens of Aggregated Tiles Refreshed Occasionally

This is the fleet overview. The problem is quantity: many components, and with SVG, many DOM nodes per chart. Updates are rare, so the three levers are keeping props stable, drawing fewer points, and sharing rendering resources.

Keep props stable so React can skip work

React's memo skips re-rendering a component when its props have not changed, with the caveat that memoization is a performance optimization and not a guarantee. Props are compared with Object.is, so passing an object or a function created during render defeats it every time.

import { memo, useMemo } from "react"; import { Line } from "react-chartjs-2"; import { Chart as ChartJS, LineElement, PointElement, LinearScale, Decimation } from "chart.js"; ChartJS.register(LineElement, PointElement, LinearScale, Decimation); // Defined once, outside the component, so its identity never changes. const options = { animation: false, // render once per update parsing: false, // data is already in { x, y } form normalized: true, // x values are sorted and unique scales: { x: { type: "linear", display: false }, y: { display: false } }, plugins: { legend: { display: false }, tooltip: { enabled: false }, decimation: { enabled: true, algorithm: "lttb", samples: 200 }, }, }; // points: [{ x, y }, ...], already aggregated on the server. export const TurbineTile = memo(function TurbineTile({ name, points }) { const data = useMemo( () => ({ datasets: [{ label: name, data: points, pointRadius: 0, borderWidth: 1.5, borderColor: "#1590c8" }], }), [name, points] ); return <Line data={data} options={options} />; }); 

The parent has to cooperate. Each tile's points array must keep its identity between renders, for example by living in state or a query cache. If the dashboard shell passes a freshly built array to every tile, the memo wrapper does nothing.

Draw fewer points than the tile can show

A tile about 100 pixels wide cannot display 1,008 points, which is seven days of 10-minute averages. Chart.js recommends decimating before rendering, setting parsing: false and normalized: true for data already in the right shape, and using animation: false so a chart renders once per update. The snippet above applies all three.

Decimation sends the chart fewer points that keep the shape of the line. The Chart.js plugin has conditions: a line dataset, a linear or time x axis, an indexAxis of 'x', parsing off, and more points than the threshold. When you control the API, aggregating on the server is cheaper than decimating in every browser, and it keeps the payload small.

Share rendering resources as the chart count climbs

With dozens of charts, per-chart setup cost starts to add up. SciChart's SubCharts API puts child charts on a single SciChartSurface, sharing one rendering canvas and engine instance. SciChart says 100 charts created individually run far slower than 100 SubCharts on one surface.

It also offers freezeWhenOutOfView, which pauses rendering for charts scrolled out of view, and native text labels for multi-chart dashboards.

These are vendor statements about the vendor's own library, and SciChart gives no measurements for them. Take the direction as useful and the magnitude as unverified.

Profile Two: One Panel Fed Continuously All Day

This is the vibration view, and its failures have little to do with chart count. They come from the default React data path: new data goes into state, the component re-renders, and the chart receives the whole dataset again. Both examples below read from this simulated 1 kHz feed, so you can run them without a backend:

// feed.js: simulated sensor feed that batches 50 samples every 50 ms. export function createVibrationFeed({ hz = 1000, batchMs = 50 } = {}) { let sample = 0; const listeners = new Set(); const timer = setInterval(() => { const n = Math.round((hz * batchMs) / 1000); const xs = new Float64Array(n); const ys = new Float64Array(n); for (let i = 0; i < n; i++, sample++) { xs[i] = sample / hz; ys[i] = Math.sin(2 * Math.PI * 50 * xs[i]) + 0.3 * (Math.random() - 0.5); } listeners.forEach((fn) => fn({ xs, ys })); }, batchMs); return { subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); }, stop: () => clearInterval(timer), }; } 

What the State-Driven Version Costs Over a Session

The obvious first version stores every sample in state and hands it to a Recharts LineChart:

import { useEffect, useState } from "react"; import { LineChart, Line, XAxis, YAxis } from "recharts"; export function StateDrivenLiveChart({ feed }) { const [points, setPoints] = useState([]); useEffect( () => feed.subscribe(({ xs, ys }) => setPoints((prev) => [...prev, ...Array.from(xs, (x, i) => ({ x, y: ys[i] }))]) ), [feed] ); return ( <LineChart width={800} height={300} data={points}> <XAxis dataKey="x" type="number" domain={["dataMin", "dataMax"]} /> <YAxis /> <Line dataKey="y" dot={false} isAnimationActive={false} /> </LineChart> ); } 

It renders correctly, and for a short history or a slow feed it is fine. The trouble is how the cost scales. [...prev, ...batch] copies the entire array on every batch, React re-renders, and the chart receives a new, longer data prop, so work per update grows with session length. At 1,000 samples per second the state holds 3.6 million objects after an hour.

Other libraries that take the full dataset as a prop and reprocess it on update behave the same way. This is a property of the pattern, not of Recharts.

Appending to the chart's own data series

The second version removes the gap: it creates the chart once and sends samples straight into its data series, so React renders the container and never sees an individual sample. This version uses SciChart.js, and this post is published for SciChart, so treat it as one way to do it.

import { memo } from "react"; import { SciChartReact } from "scichart-react"; import { SciChartSurface, NumericAxis, FastLineRenderableSeries, XyDataSeries, EAutoRange, } from "scichart"; // Load the WebAssembly engine from SciChart's CDN. Call once, before the first chart. SciChartSurface.loadWasmFromCDN(); const WINDOW_POINTS = 5000; async function initChart(rootElement: string | HTMLDivElement) { const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement); sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { autoRange: EAutoRange.Always })); sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { autoRange: EAutoRange.Always })); // Rolling window: once 5,000 points are stored, each append drops the oldest. const dataSeries = new XyDataSeries(wasmContext, { fifoCapacity: WINDOW_POINTS, dataIsSortedInX: true, // x only ever increases dataEvenlySpacedInX: true, // fixed sample rate containsNaN: false, // the feed never sends gaps }); sciChartSurface.renderableSeries.add( new FastLineRenderableSeries(wasmContext, { dataSeries, strokeThickness: 2 }) ); return { sciChartSurface, dataSeries }; } type VibrationFeed = { subscribe: (fn: (b: { xs: Float64Array; ys: Float64Array }) => void) => () => void; }; function LivePanelBase({ feed }: { feed: VibrationFeed }) { return ( <SciChartReact style={{ width: "100%", height: 400 }} initChart={initChart} // Runs once after the chart exists. Samples go straight into the data // series, so React never re-renders per sample. The returned function // runs on unmount and closes the subscription. onInit={({ dataSeries }) => feed.subscribe(({ xs, ys }) => { dataSeries.appendRange(xs, ys); }) } /> ); } export const LivePanel = memo(LivePanelBase); 

Install it with npm install scichart scichart-react react react-dom. Wrapper version 2.x of scichart-react requires scichart 6.0.13 or later, and initChart must not change between renders, so this panel defines it at module level.

This is the wrapper's standard initChart and onInit pattern applied to a fifoCapacity series. SciChart has not published it as an official sample.

Three details do the work:

  • fifoCapacity. A FIFO (first in, first out) series is handled internally as a circular buffer, while a plain series keeps growing as you append until you stop or call clear().
  • Batching. SciChart recommends appendRange() over single-point calls, and its own example puts 100,000 single appends at about 69 ms against about 1 ms for one batch, on hardware it does not state.
  • Throttled redraws. A redraw happens at most once every 1/60th of a second however often you update, so data arrival and drawing are decoupled.

The two versions are not a like-for-like comparison. The state-driven chart keeps every sample, while the SciChart panel holds at most 5,000 points, so part of the gain comes from the cap itself.

You can cap the Recharts version too, with [...prev, ...batch].slice(-5000), and memory stays flat. It still copies the window and re-renders React on every batch, whereas the SciChart panel appends into a circular buffer that React never touches.

Infographic: work per update across a one-hour session. With every sample kept in React state the work keeps rising. With a capped data series fed directly the work stays flat.

Cleaning Up When the Panel Unmounts or Switches

On unmount, the wrapper runs the cleanup function returned by onInit, calls onDelete if you gave one, and deletes the chart surface. Deleting the surface also deletes its data series, while series you add and remove dynamically must be deleted manually.

Returning the unsubscribe function from onInit is what stops a remount from leaving a second subscription running.

Switching turbines needs one more step. onInit runs once per chart, so if the shell passes a different feed to a panel that is already mounted, the panel keeps appending from the old turbine. Give the panel a key tied to the selection, and React unmounts the old panel, runs its cleanup, and mounts a fresh one with an empty series:

// In the dashboard shell. feeds holds one feed per turbine, created outside the panel. <LivePanel key={selectedTurbineId} feed={feeds[selectedTurbineId]} /> 

Setup Points to Settle Before Shipping

Two setup points are worth handling early:

  • The v6 engine is a directory of WebAssembly files, so either call loadWasmFromCDN() once, as above, or copy the _wasm directory into your build output.
  • The Community Edition is free for personal, educational, and non-commercial use and shows a watermark. Each build expires six months after its build date, so free users need to stay on a recent version. Commercial projects need a paid licence, priced per developer on the SciChart shop.

Profile Three: A Dashboard With One Live Panel Inside

Most real screens land here: a dashboard of aggregated tiles with one live panel in the corner. The fix is a boundary, not a new library.

  • Keep the shell in ordinary React, with aggregated data and memoized tiles.
  • Give the live panel its own component that owns its data series, buffer, and subscription.
  • Pass only the selection and time window down. Let the panel report back only low-frequency events, so raw samples never cross that boundary.

The failure modes are quiet. A memoized tile re-renders when a parent hands it a new object each render, and a live chart grows without limit when nothing caps its buffer. Keying the live panel on the selected turbine handles the third one: stale subscriptions after a switch.

Infographic: a dashboard shell in ordinary React on one side and a live panel on the other. The selection and time window pass down, low-frequency events pass up, and raw samples go from the feed straight to the live panel.

Profile Four: A Small Team Whose Charts Already Work Fine

If your Recharts or Chart.js setup works, your data is aggregated, and nobody is complaining about frame rate, stay where you are. SVG and canvas libraries remain the better fit for a dashboard refreshed every minute or on a filter change, and for teams where a smaller bundle outweighs headroom.

The signal to look past them is a continuous feed, a long-lived session, or a window that has to keep growing. Those are the conditions where the state-driven pattern's cost keeps rising, and where a data series that lives outside React earns the engine it needs.

What Published Benchmarks Show About Streaming Charts

Published measurements here are thin, and it helps to know how thin before you rely on one. The most detailed public figure comes from uPlot's README: updating 3,600 points at 60 fps uses 10% CPU and 12.3 MB, against 40% and 77 MB for Chart.js and 70% and 85 MB for ECharts.

Read it with its conditions in mind:

  • It comes from one run on 2023-03-11, an AMD Ryzen 7 PRO 5850U with Chrome 113 at a 1.5 device pixel ratio.
  • It compares canvas libraries only, and it is published by the author of the library that comes out ahead.
  • It does not involve React.

SciChart's benchmark post is also vendor-run, says its tests run for several seconds, and has no React test. I found no independent, method-disclosed benchmark of React charting under 30 or more minutes of streaming, so this post gives no "N times faster" figure. To get a number you can rely on, test your own workload:

  • Data: your largest realistic dataset, real chart count, and real update rate, including the longest session a user will leave open.
  • Measure: heap size and dropped frames after 30 minutes of continuous updates, update-to-screen latency, and React commits per second from the Profiler for the shell around the chart.
  • Hardware: your lowest-spec target machine, and a remote desktop session if users connect that way, since GPU-backed charts depend on what the machine exposes.
  • Startup: the JavaScript and WebAssembly payload and time to first chart. The config-based scichart-react component adds about 205 KB gzip over an initChart chart, which is why the example above uses initChart.

Where Should You Start With React Charts at Scale

A dashboard grows in chart count, so its fixes are server-side aggregation, stable props, decimation, and shared rendering resources. A live view grows in time, so its fixes are a direct update path that skips React state, a bounded buffer, and cleanup that survives remounts. Freshness, update rate, and aggregated versus raw data tell you which one each panel is, and the published numbers show direction without settling magnitude, so the final check is always your own data.

Sort each panel in your app with those three questions. Keep aggregated dashboards on SVG or canvas libraries with memoized props and decimation, then move any continuously fed panel to a chart whose data lives outside React, with a capped buffer. To try the pattern, follow the SciChart.js getting-started guide, then measure heap and dropped frames over a 30-minute session. I first wrote this up on Substack, and I would like to hear which profile your busiest panel falls into.

Frequently Asked Questions About React Data Visualization

Should chart data live in React state?

For dashboards, usually yes, because updates are infrequent and state keeps the code predictable. For continuous feeds, no. Hold a reference to the chart's own data container and append to it directly, so React does not re-render for every batch of samples.

Why does my React chart get slower the longer the page stays open?

Check whether each batch of new data is copied into a growing array in state and passed back to the chart as a prop. That makes the work per update grow with session length. Cap the history with a rolling window, such as fifoCapacity in SciChart.js, and append to the chart's data series instead.

Do I need WebGL or WebGPU for a dashboard?

Usually not. A dashboard of aggregated data refreshed on a schedule works with SVG or canvas libraries, and the larger gains come from decimation, server-side aggregation, and keeping memoized components from re-rendering. GPU rendering helps most when chart count or point count is high enough that those steps are not enough.

Does scichart-react clean up the chart when a component unmounts?

Yes. The wrapper runs the cleanup function returned by onInit, calls onDelete, and deletes the chart surface. Return your unsubscribe function from onInit, and delete any series you add or remove dynamically yourself.

Which scichart-react version goes with which scichart version?

Wrapper 2.x requires scichart 6.0.13 or later. For scichart 3.x to 5.x, use scichart-react 1.x. In 2.x, SciChartReact takes initChart, and the config prop moved to a separate SciChartDeclarative component.

原文:https://www.a8q9.cn/en/article/react-data-visualization-matching-chart-choices-to-how-fast-your-data-moves-192fff.html

相关文章