Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading