Abel
Abel

Reputation: 1614

setState array cause infinite loop

I have lists of arrays created from sampling size. When I setState the array with the entire new array. I got an error of infinite loop.

Code

const sampleData = _.fill(Array(200), 0)
const [value, setValue] = useState(sampleData)

setValue(value.fill(100)) // Error

Error

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

Upvotes: 0

Views: 330

Answers (1)

priyanka nishad
priyanka nishad

Reputation: 26

You should not call setter functions returned from useState during renders. They either need to be called in hooks(useEffect, useCallback, useLayoutEffect) callbacks or in non render phases, like event handlers.

In this case, you can do something like this:

const sampleData = _.fill(Array(200), 0);
const [value, setValue] = useState(sampleData);

useEffect(() => {
  setValue(value.fill(100)); // Error
}, []);

Upvotes: 1

Related Questions