Home > Net >  React JS - Infinite Loop issue
React JS - Infinite Loop issue

Time:10-22

I'm trying to add some graphs/barcharts to a react component but keep getting an issue with infinite loops. I've tried this link I found online but I wasn't able to make it work with my code. https://alexsidorenko.com/blog/react-infinite-loop/

const MyComponent = ({ someInput }) => {
  const [state2, setState2] = useState([]);

  useEffect(() => {
    setState2({
      labels: ["January", "February", "March", "April", "May"],
      datasets: [
        {
          label: "Rainfall",
          backgroundColor: [
            "#B21F00",
            "#C9DE00",
            "#2FDE00",
            "#00A6B4",
            "#6800B4",
          ],
          hoverBackgroundColor: [
            "#501800",
            "#4B5000",
            "#175000",
            "#003350",
            "#35014F",
          ],
          data: [65, 59, 80, 81, 56],
        },
      ],
    });
  }, []);

  return (
    <div className="search">
      <Bar data={state2} />
    </div>
  );
};

export default MyComponent;

CodePudding user response:

Move the default value your trying to set within useeffect into the useState method call.

    const MyComponent = ({someInput}) => {
    const [state2, setState2] = useState({
      labels: ["January", "February", "March", "April", "May"],
    datasets: [
    {
      label: "Rainfall",
    backgroundColor: [
    "#B21F00",
    "#C9DE00",
    "#2FDE00",
    "#00A6B4",
    "#6800B4",
    ],
    hoverBackgroundColor: [
    "#501800",
    "#4B5000",
    "#175000",
    "#003350",
    "#35014F",
    ],
    data: [65, 59, 80, 81, 56],
        },
    ],
    });

    useEffect(() => {

    }, []);

    return (
    <div className="search">
      <Bar data={state2} />
    </div>
    );
  };

  export default MyComponent;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The setState2(... call inside useEffect callback is causing the component to be rerendered, therefore the useEffect to be called again resulting in an infinite loop.

As for the fix you need to check if the state2 needs to be updated. So either check if state2 is defined inside the useState callback. either set a flag.

Or if you are doing a request and you want to see if anything changes just check that (by comparing the JSON.stringify() values)

  • Related