Home > Mobile >  ChartJS in React throws 'too may re-renders'
ChartJS in React throws 'too may re-renders'

Time:05-21

I am trying to create bar chart using the ChartJS. When I start my app, there is nothing on web-page, and some errors in console: 'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

my code:

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js'
import {Bar} from 'react-chartjs-2'
import React, {useState, useEffect} from 'react'

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

function App() {

  const [chartData, setChartData] = useState({
    datasets:[],
  })

  const [chartOptions, setChartOptions] = useState({});

  useEffect(()=>{
    setChartData({
      labels: ['john','kevin','george','mike','oreo'],
      datasets:[
        {
          label: 'label',
          data: [12,55,34,120,720],
          borderColor: 'green',
          backgroundColor: 'blue',
        },
      ],
    })
  },[])
  setChartOptions({
    responsive:true,
    plugins:{
      legend:{
        position:'top'
      },
      title:{
        display:true,
        text:'text from tittle'
      }
    }
  })


  return (
    <div className="App">
      <Bar options={chartOptions} data={chartData}/>
    </div>
  );
}

error: Too many re-renders. React limits the number of renders to prevent an infinite loop

what should I do to see chart on my web-page?

CodePudding user response:

You need to add a dependency array to useEffect. Excluding items from the dependency array may lead to an infinite chain of updates.

Add the dependency array as the second parameter of useEffect:

  useEffect(()=>{
    setChartData({
      labels: ['john','kevin','george','mike','oreo'],
      datasets:[
        {
          label: 'label',
          data: [12,55,34,120,720],
          borderColor: 'green',
          backgroundColor: 'blue',
        },
      ],
    })
  },[])
  setChartOptions({
    responsive:true,
    plugins:{
      legend:{
        position:'top'
      },
      title:{
        display:true,
        text:'text from tittle'
      }
    }
  }, [chartOptions, chartData]) // effect will run when either changes

Want to run the effect only once?

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

Find out more in the docs

  • Related