Chartjs-Destroying Chart js within useEffect – React

1πŸ‘

βœ…

In the new docs they also use this, they solved it by destroying the chart in the return of the use effect like this:

useEffect(() => {
    const cfg = {
      type: 'doughnut',
      data: {
        labels: [
          'Red',
          'Blue',
          'Yellow'
        ],
        datasets: [{
          label: 'My First Dataset',
          data: [300, 50, 100],
          backgroundColor: [
            'rgb(255, 99, 132)',
            'rgb(54, 162, 235)',
            'rgb(255, 205, 86)'
          ],
          hoverOffset: 4
        }]
      }
    };
    const chart = new Chart(canvas.current.getContext('2d'), cfg);
    return () => chart.destroy();
  });

Link to their doc with live example: https://www.chartjs.org/docs/master/charts/doughnut/

Leave a comment