I'm building a React-based admin dashboard that displays user engagement over time using Chart.js
. The chart should update dynamically when new data is fetched from an API.
import React, { useRef, useEffect } from 'react';
import { Chart } from 'chart.js/auto';
const LineChart = ({ data }) => {
const chartRef = useRef(null);
useEffect(() => {
const ctx = chartRef.current.getContext('2d');
const chartInstance = new Chart(ctx, {
type: 'line',
data: {
labels: data.labels,
datasets: [
{
label: 'Users',
data: data.values,
borderColor: 'blue',
},
],
},
});
}, [data]);
return <canvas ref={chartRef} />;
};
export default LineChart;
When the data prop changes, the chart overlaps with the previous instance rather than updating cleanly.
It's impractical to create a new instance on each data change, it's persistent through the component lifecycle. Instead, data needs to be updated on existing instance. The instance needs to be cleaned up on component unmount in order to prevent memory leaks:
...
const chartRef = useRef(null);
const chartInstance = useRef(null);
useEffect(() => {
const ctx = chartRef.current.getContext('2d');
chartInstance.current = new Chart(...);
return () => chartInstance.current.destroy();
}, []);
useEffect(() => {
chartInstance.current.dataset.data = data.values;
chartInstance.current.update();
}, [data]);
...