Home > database >  React useState array stays empty on first update
React useState array stays empty on first update

Time:01-27

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?

CodePudding user response:

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

  • Related