Every charting tutorial uses a clean dataset of twelve monthly values. Real time-series data is nothing like that: irregular intervals, gaps where the device dropped off, a counter that resets at 3am for no reason you can find, and far more points than pixels. Home Assistant produces all four, which makes it an unusually good place to learn the parts that tutorials skip. If you want the household side first, meaning which meters and plugs feed these sensors, smart energy management for homes covers where the numbers come from.
A note on where I'm coming from, so nothing here reads as more than it is. My own Home Assistant front end, a Vite + React app, draws its charts with Chart.js, not Recharts. The energy data behind it comes from a meter on the whole house plus per-circuit and per-socket meters. Recharts is here because it's the common React choice, and the bucketing and decimation below are plain TypeScript that doesn't care which library draws the result.
What the history endpoint returns
One GET, one token, one entity:
const start = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const params = new URLSearchParams({
filter_entity_id: "sensor.house_power",
end_time: new Date().toISOString(),
minimal_response: "true",
no_attributes: "true",
});
const res = await fetch(`${BASE}/api/history/period/${start}?${params}`, {
headers: { Authorization: `Bearer ${TOKEN}` },
});
const [series]: RawState[][] = await res.json();
The nesting catches everyone once: the response is an array of arrays, one per entity, even when you asked for a single entity. And every state is a string, as covered in our guide to typing Home Assistant data in TypeScript, so parsing happens here rather than in the chart component.
minimal_response and no_attributes together cut a day of one power sensor from several megabytes to a few hundred kilobytes. On a wall panel over Wi-Fi that difference is the gap between a chart that appears and one that hangs.
Bucketing depends on the sensor type
Aggregation is where the domain knowledge lives: the two sensor types below need different arithmetic.
A temperature sensor is a measurement. Its value at any moment stands alone, so an hourly bucket is the mean of the values inside it, and min and max are worth keeping alongside.
An energy sensor is usually total_increasing, a running total in kWh that only rises and now and then restarts from zero. Averaging it produces a number with no physical meaning. What you want per bucket is the last value minus the first, the consumption during that window.
interface Bucket { t: number; value: number; min?: number; max?: number }
function bucketMeasurement(points: Point[], ms: number): Bucket[] {
const groups = new Map<number, number[]>();
for (const p of points) {
const key = Math.floor(p.t / ms) * ms;
const list = groups.get(key);
if (list) {
list.push(p.value);
} else {
groups.set(key, [p.value]);
}
}
return [...groups.entries()]
.map(([t, vals]) => ({
t,
value: vals.reduce((a, b) => a + b, 0) / vals.length,
min: Math.min(...vals),
max: Math.max(...vals),
}))
.sort((a, b) => a.t - b.t);
}
function bucketCounter(points: Point[], ms: number): Bucket[] {
// points arrive in time order, as the history endpoint returns them
const totals = new Map<number, number>();
let prev: number | undefined;
for (const p of points) {
const key = Math.floor(p.t / ms) * ms;
let delta = 0;
if (prev !== undefined) {
const diff = p.value - prev;
if (diff >= 0) {
delta = diff;
} else if (-diff >= prev * 0.1) {
// Home Assistant's rule: a drop of 10% or more is a reset,
// and the first value after it counts in full.
delta = p.value;
}
// A smaller drop is noise and adds nothing.
}
totals.set(key, (totals.get(key) ?? 0) + delta);
prev = p.value;
}
return [...totals.entries()]
.map(([t, value]) => ({ t, value }))
.sort((a, b) => a.t - b.t);
}
That negative-delta branch is the counter-reset handling. A device reboots, the counter goes back to zero, and without it the chart shows a large negative bar for the hour it happened. The 10% threshold is not mine: the Home Assistant sensor docs linked above say that for total_increasing a drop of less than 10% is treated as noise, not as a reset, while a larger drop starts a new cycle that counts from zero, so the first value after it is added in full. Mirroring that rule means your chart agrees with the Energy dashboard instead of arguing with it. Note that prev survives from one bucket to the next. Take the deltas only inside each bucket and the consumption between the last reading of one hour and the first reading of the next disappears; with a meter that reports every five minutes, that's one interval in twelve, missing from every hourly bar.
Downsampling without deleting the spikes
Once bucketed you may still have more points than pixels, and the obvious fix, keeping every Nth point, is the wrong one. Sampling drops whichever points it doesn't land on, and the interesting ones, the 3kW spike when the kettle and the oven overlapped, are exactly the ones most likely to disappear.
Min-max decimation keeps them. Divide the series into as many windows as you have target points, and emit both the minimum and the maximum from each window in their original time order:
function decimate(points: Bucket[], target: number): Bucket[] {
if (points.length <= target) {
return points;
}
const windowSize = Math.ceil(points.length / (target / 2));
const out: Bucket[] = [];
for (let i = 0; i < points.length; i += windowSize) {
const slice = points.slice(i, i + windowSize);
let lo = slice[0];
let hi = slice[0];
for (const p of slice) {
if (p.value < lo.value) {
lo = p;
}
if (p.value > hi.value) {
hi = p;
}
}
if (lo.t <= hi.t) {
out.push(lo, hi);
} else {
out.push(hi, lo);
}
}
return out;
}
The output is visually indistinguishable from the full series at chart resolution, and it is a fraction of the DOM nodes.
Recharts config for real data
Two settings matter more than the rest.
connectNulls={false} on the line. Home Assistant sensors go unavailable, and a chart that bridges a four-hour gap with a straight line is showing data that never existed. Let the gap be visible. The setting only acts on null values, though, and the bucketing above emits nothing at all for an empty hour, so on a numeric time axis Recharts would still draw straight across it. Put a null into the gap before the data reaches the chart:
type ChartPoint = { t: number; value: number | null };
function breakGaps(points: Bucket[], maxGapMs: number): ChartPoint[] {
const out: ChartPoint[] = [];
for (const p of points) {
const last = out[out.length - 1];
if (last && p.t - last.t > maxGapMs) {
out.push({ t: last.t + 1, value: null });
}
out.push(p);
}
return out;
}
Pick maxGapMs comfortably above the spacing decimation can produce, an hour for 15-minute buckets, so only a real outage breaks the line.
Explicit domain on the Y axis for anything with a meaningful floor. Power draw starts at zero. Recharts' own default for a numeric axis is [0, 'auto'] (it's the defaultNumericDomain constant in the library's axis selectors), so writing it out is restating the default, and I do it anyway because the YAxis docs list ['auto', 'auto'] and ['dataMin', 'dataMax'] among their examples, and a config copied from one of those starts the axis at the lowest reading. On a house that idles at 1,800W that turns a 5% variation into a chart that looks like a cliff.
<ResponsiveContainer width="100%" height={280}>
<LineChart data={breakGaps(decimated, 60 * 60 * 1000)}>
<XAxis
dataKey="t"
type="number"
scale="time"
domain={["dataMin", "dataMax"]}
tickFormatter={(t) => new Date(t).toLocaleTimeString([], { hour: "2-digit" })}
/>
<YAxis domain={[0, "auto"]} unit=" W" width={70} />
<Tooltip labelFormatter={(t) => new Date(Number(t)).toLocaleString()} />
<Line type="monotone" dataKey="value" dot={false} connectNulls={false} strokeWidth={2} />
</LineChart>
</ResponsiveContainer>
That config is for the power sensor, which is a measurement in watts. Feed it bucketCounter output and each bar is kWh per bucket, so change unit to match.
dot={false} is not cosmetic either. At 600 points, individual dots are both unreadable and a meaningful share of the render cost.
Why aggregation is the hard part
This article spends most of its length on data preparation rather than on chart configuration, which surprises people coming from tutorials where the chart is the whole exercise.
A chart library takes an array and draws it. That part is solved, and any of the mainstream options will produce something reasonable from clean input. What none of them can do is decide what a point in your series means, and that decision is domain knowledge that has to happen before the data reaches the component. Averaging a counter, sampling away a spike, or bridging a four-hour outage with a straight line are all mistakes the renderer will execute faithfully and without complaint, and every one of them produces a chart that looks completely convincing while being wrong.
That is the failure to guard against. A crash gets noticed and fixed. A chart that understates your peak load because the decimation dropped it informs decisions, and nobody goes back to check the aggregation because the picture looked plausible from the start.
A chart that crashes gets fixed the same afternoon; a chart that quietly understates your peak load gets believed for months.
So the useful habit is to treat the transformation from raw states to chart-ready buckets as its own module with its own tests, well away from any React component. Feed it a fixture containing a counter reset, a gap, and a burst of duplicated timestamps, all of which a real Home Assistant instance produces sooner or later, and assert on the numbers rather than eyeballing the output. The case to write first: I ran bucketCounter from above on six readings inside one hour, 1200.0, 1200.4, 1200.9, 0.1, 0.5, 1.0, where the counter resets after the third. Without the reset branch the bucket comes out at about -1,200 kWh; with it, about 1.9, because the drop from 1200.9 to 0.1 is far past the 10% line and the 0.1 is added in full. On screen the first result is one odd bar you might blame on the sensor. As an assertion it fails in a single line, and I'd take the assertion every time. The second case puts a reading at 12:55 and the next at 13:05 and checks that the 13:00 bucket includes the step between them.
There is a second reason to keep the two layers apart. Charting libraries go out of fashion faster than data does. The bucketing and decimation logic here is plain TypeScript over plain arrays, so moving from Recharts to something canvas-based later is an afternoon of component work rather than a rewrite. Coupling the aggregation to the renderer is what turns that afternoon into a fortnight. It's also why I'm comfortable walking through Recharts here while using Chart.js myself: the part worth getting right lives in neither.
How many points get rendered
Take one day of one power sensor at 10-second resolution. That's 8,640 raw points:
| Approach | Points rendered |
|---|---|
| Raw series | 8,640 |
| Hourly buckets only | 24 |
1-minute buckets (1,440) plus decimate with a target of 600 | 576 |
Recharts draws every point as SVG, so render cost grows with that first column. These three rows were not timed, so there are no millisecond figures here; profile your own tablet with the React DevTools Profiler before you pick a resolution. The middle row is cheap and hides everything interesting inside each hour. The last row is the one worth shipping: 15 times fewer SVG nodes than the raw series, with the peaks kept. (Fifteen-minute buckets give only 96 points, already under the target, so decimate returns them untouched.)
Most charting tutorials are framed around the library, and in this one the library is almost incidental, which is why the same code moves to a different renderer in an afternoon.