Video wird geladen...
Video konnte nicht geladen werden
"Why can't I access an updated state value in React immediately?"
142,247 Aufrufe • vor 3 Jahren •via X (Twitter)
9 Kommentare

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.

Shyam Makwanavor 3 Jahren
Other solution is to use callback function like:

Neo 🍍🍍vor 3 Jahren
There’s a callback on setState if you need it immediately

Bilal Tamerhoulet 🇩🇿 🇵🇸vor 3 Jahren
State updates are asynchronous

harpaljadeja.eth (evm/acc) 🇮🇳vor 3 Jahren
So what's the solution?

🦭xvor 3 Jahren
Closure

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.

nadimvor 3 Jahren
What are you using to create this awesome code animation?

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