1

I have a quick question about how React changes a function component sate using hooks. I am fetching some data from ASW RDS MySQL database. The relevant piece of code looks as follows:

const [data, upDateData] = React.useState([]);

.....

async function load() {
    let response = await fetch("/api/employee");
    let body = await response.json();
    upDateData(body);
    console.log(body);
    console.log(data)
}

My question is the following. When I console log the "body" variable which is the actual response, I get an array of Json objects, exactly what I expect. However, when I do the same with my "data" variable defined in the hook, I get an empty array even though I console log after the updateData function has been called and the value of "data" has (presumably) been changed. Could somebody explain why that is? I suspect that this may have something to do with async nature of the function but I am not sure. Thank you in advance!

  • Possible duplicate of https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Shubham Sharma Apr 01 '20 at 06:06
  • 1
    State updates in React (whether for class or functional components) are asynchronous. So you can't console.log them on the next line and expect them to be different – Jayce444 Apr 01 '20 at 06:09

1 Answers1

1

Yes you are right, the state update is async and you cannot get the data immediately after update.

setState actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this. Thus the setState calls are asynchronous as well as batched for better UI experience and performance. This applies on both functional/Class components.

From React documentation

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

You could read more about this here

Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42