Video wird geladen...

Video konnte nicht geladen werden

Zur Startseite

"Why can't I access an updated state value in React immediately?"

142,247 Aufrufe • vor 3 Jahren •via X (Twitter)

9 Kommentare

Profilbild von Alex Sidorenko
Alex Sidorenkovor 3 Jahren

Because it's not how React works. Updating a state in React triggers a new render (React calls your component function again with a new state). You can access the updated state variable during this new render.

Profilbild von Shyam Makwana
Shyam Makwanavor 3 Jahren

Other solution is to use callback function like:

Profilbild von Neo 🍍🍍
Neo 🍍🍍vor 3 Jahren

There’s a callback on setState if you need it immediately

Profilbild von Bilal Tamerhoulet 🇩🇿 🇵🇸
Bilal Tamerhoulet 🇩🇿 🇵🇸vor 3 Jahren

State updates are asynchronous

Profilbild von harpaljadeja.eth (evm/acc) 🇮🇳
harpaljadeja.eth (evm/acc) 🇮🇳vor 3 Jahren

So what's the solution?

Profilbild von 🦭x
🦭xvor 3 Jahren

Closure

Profilbild von Eberechi
Eberechivor 3 Jahren

React batches changes and updates only after the whole function is done running. Hence a log immediately after changing set only had access to the initial state.

Profilbild von nadim
nadimvor 3 Jahren

What are you using to create this awesome code animation?

Profilbild von Claudio
Claudiovor 3 Jahren

Nice content mate, but it never ceases to amaze me how weirdly architected React is.

Ähnliche Videos