Infinite Loop when using setState for array

I believe you may be experiencing issues because calling setStringArray is a ‘side effect’.

This will cause the function component to be re-rendered infinitely, due to the hook having updated the component’s state, causing a re-render which then updates the state and on and on infinitely.

Essentially, you shouldn’t be trying to both read and update strArray in the same line.

You should simply only call the setStrArr once after having fully populated your array.

I think you should also look into using the useEffect hook for behaviour like this.

The last parameter it get’s passed tells React to only run the code inside of this useEffect hook if the paramater given (strArray in this case) changes.

This hook is designed for when you want to have ‘side effects’ in your component.

So perhaps you could try something like to prevent your infinite re-renders:

function MyApp(){
  const [strArr, setStrArr] = useState([]);

  useEffect(() => {
     const fourHiArray = [];

    for(let i = 0; i<4; i++){
       fourHiArray = ([...fourHiArray, "hi"])
       if(i==3){
          console.log("done")
       }
    } 

    setStrArr(fourHiArray);
  }, [strArr]);
       
  return(
    <div>
    </div>
  )
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top