reactjschart.js

Chart.js React Integration on admin dashboard


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.


Solution

  • You can destroy the previous chart before creating a new one

    import { Chart } from 'chart.js/auto';
    
    const LineChart = ({ data }) => {
      const chartRef = useRef(null);
      const chartInstanceRef = useRef(null); // Store the Chart instance
    
      useEffect(() => {
        const ctx = chartRef.current.getContext('2d');
    
        // Destroy the previous chart if it exists
        if (chartInstanceRef.current) {
          chartInstanceRef.current.destroy();
        }
    
        // Create new chart
        chartInstanceRef.current = new Chart(ctx, {
          type: 'line',
          data: {
            labels: data.labels,
            datasets: [
              {
                label: 'Users',
                data: data.values,
                
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
          },
        });
      }, [data]);
    
      return <canvas ref={chartRef} />;
    };
    
    export default LineChart;