React Too Many Re-renders Problem

Hi, It’s obvious that React re-renders the whole component and its child components when it’s state changes. I’m trying to change the state inside the component and it’s showing the infinite loop. My code was

import {useState} from "react";

export default function TestComponent(){
    let [test, setTest] = useState("");
    
    let array = [];

    function norman(){
        for(let i=0;i<9;i++){
            array.push(i);
        }
        return array;
    }

    norman();

    setTest(()=>array);
    
    return<>
     {<p>
        {test}
    </p>}
    </>
}

How can I change the state inside component with out getting infinite loop

Hi @mallik7041,

Let’s start by walking through your code:

  1. First, you create a test state with the useState hook. You give it an empty string as the initial value.
  2. Also, you declare a variable named array with an empty array value.
  3. Then you create a function named norman. The function updates the array variable with numbers 0 to 9. And it returns the array variable.
  4. You call the norman function.
  5. You update the test state as the array variable.

I will limit my explanation to your request and ignore the other problems in your code.

When you change a state, React re-runs the component. So when you update the state in step 5, React re-runs from step 2. It re-creates the array variable the norman function and the operations again. When it hits the state update line, it re-runs step 2, and so on.

If you just want to run your setTest function when the component mounts, you can use useEffect.

import { useEffect, useState } from "react";

export default function SomeComponent() {
  const [someState, setSomeState] = useState("old state");

  useEffect(() => {
    setSomeState("new state");
  }, []);

  return <p>{someState}</p>;
}

useEffect takes a function to run as the first parameter, and takes a dependency array as the second parameter. If you give it an empty array, this means: run this function only in the first mount.

If you want to learn more about useEffect, you can check useEffect section in React documentation.

Also, I definitely recommend you check the Learn React section in React documentation to better understand how React works.

Happy coding!

It would help if you explained what you actually are trying to do. Because if you just want the initial state to be an array of elements 0 to 9, there are easier and more readable ways of doing that.

But I suspect this code is just an example of something else you are trying to do, and without the proper context, any answer given will not address your actual need.

1 Like