简体   繁体   中英

React:- useState Hook value not updating for dictionary and array

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM