'Updating state with new array in React using hooks

I have a state of array in a React functional component like this -

const [columns, setColumns] = React.useState<[]>([])

I wish to update the entire array at some time (instead of updating some particular element of pushing/deleting some element). Can I simply do setColumns(newArray) ? Upon doing so, my React component is going into an infinite loop for some reason. Pls help.



Solution 1:[1]

So, it was a very silly bug. I was updating the state inside the body of the functional component. As a result, each state update led to a re-render which led to another state update and so on. Solution was to have the state update based on some condition/function/hook. In my case, I added it inside the useEffect hook which executes only when one of it's dependencies changes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shreyansh