Ash
Ash

Reputation: 64

React useState array stays empty on first update

const [liveRows, setLiveRows] = useState([]);

function addRow(arr){

    setLiveRows([...liveRows, arr]);

    console.log(liveRows)

}

When I run the addRow function with an array, the map used in the page re-renders fine, but the array in the log shows empty.

Running the function again shows the previous state of the array before the update, but the re-render shows correctly.

I am assuming this is due to the spread but am lost how to correct it?

Upvotes: 1

Views: 873

Answers (1)

HussainCo
HussainCo

Reputation: 36

This is expected behavior. setState is not an asynchronous! setState always work after the next render.

The set function only updates the state variable for the next render. If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call.

For details : https://beta.reactjs.org/reference/react/useState

Upvotes: 2

Related Questions