Home > Mobile >  Why is my component throwing a "too many re-renders" error?
Why is my component throwing a "too many re-renders" error?

Time:08-25

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

I couldn't find where the loop is, I managed to check if the states are different from "null" I could only render the graph and avoid the error, but it persists, could someone help me?..

import React from "react";
import { useState } from "react";
import { Chart } from "react-google-charts";

export const StatusChart = (pokemon) => {
  const [hp, setHp] = useState(null);
  const [attack, setAttack] = useState(null);
  const [defense, setDefense] = useState(null);
  const [specialAtack, setSpecialAtack] = useState(null);
  const [specialDefese, setSpecialDefese] = useState(null);
  const [speed, setSpeed] = useState(null);

  console.log(
    pokemon.pokemon.map((e) => {
      console.log(e.base_stat);
      switch (e.stat.name) {
        case "hp":
          setHp(e.base_stat);
          break;
        case "attack":
          setAttack(e.base_stat);
          break;
        case "defense":
          setDefense(e.base_stat);
          break;
        case "special-attack":
          setSpecialAtack(e.base_stat);
          break;
        case "special-defense":
          setSpecialDefese(e.base_stat);
          break;
        case "speed":
          setSpeed(e.base_stat);
          break;
      }
    })
  );

  const data = [
    ["Status", "Value", { role: "style" }],
    ["HP", hp, "red"],
    ["Atack", attack, "orange"],
    ["Defese", defense, "green"],
    ["Special Atack", specialAtack, "gold"],
    ["Special Defense", specialDefese, "purple"],
    ["Speed", speed, "blue"],
  ];

  return (
    <>
      {hp ||
      attack ||
      defense ||
      specialAtack ||
      specialDefese ||
      speed === null ? null : (
        <Chart
          chartType="ColumnChart"
          width="100%"
          height="300px"
          data={data}
        />
      )}
    </>
  );
};

Github link: https://github.com/yjdutra/pokedex-pokeapi

CodePudding user response:

This console.log with a map inside is doing many setStates at the same time, causing the UI to re-render at each "pokemon" entity that you have. This is causing the error.

  • Related