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.