0

For Array and Dictionary useState hook is not updating it's value.

My Method:-

const [saveresponse, setSaveResponse] = useState({})

For to update saveresponse:-

const res={a:"1",b:"2"}
setSaveResponse(res)

Example function:-

 const ComputeAndSaveTest = () => {
    const res={a:"1",b:"2"}
    setSaveResponse(res)
    console.log(saveresponse) //Not updating
  
  }

Also another function call after that function:-

onCompleted() {
     console.log(saveresponse)  //Not Updated
    }

Same applied to Array.

I am new to react someone please suggest me best practice to solve it and please explain it if possible.

Thank you!

dattu
  • 43
  • 4
  • Calling `setSaveResponse` in the way that you do should update the state indeed. What makes you think the value is not updated? – Phil Jul 12 '22 at 13:29
  • 3
    You have to provide a more complete example. How do you verify that the value doesn't update? My suspicion is a stale callback function. `saveresponse` will only be updated in the *next* render and any function that uses `saveresponse` needs to depend on it so that it gets recreated. Otherwise those functions will refer to an older value. – Felix Kling Jul 12 '22 at 13:29
  • Yes, `saveresponse` will still refer to the old value after calling `setSaveResponse()`. See [The useState set method is not reflecting a change immediately](https://stackoverflow.com/q/54069253/218196). The issue with `onCompleted` might be the same but there is not enough context to say for sure. – Felix Kling Jul 12 '22 at 14:47

1 Answers1

0

State updates in React are batched into one asynchronous update. The motivation for this behavior is the fact that state change triggers a re-render, which is an expensive operation for React's virtual DOM. Therefore, if you set state and then immediately print it, the change still won't be reflected. Only after the next render it will be reflected. You can read more about it in this article.

Omry
  • 16
  • 2