Loading video...

Video Failed to Load

Go Home

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

142,247 views • 3 years ago •via X (Twitter)

9 Comments

Alex Sidorenko's profile picture
Alex Sidorenko3 years ago

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 Makwana's profile picture
Shyam Makwana3 years ago

Other solution is to use callback function like:

Neo 🍍🍍's profile picture
Neo 🍍🍍3 years ago

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

Bilal Tamerhoulet 🇩🇿 🇵🇸's profile picture
Bilal Tamerhoulet 🇩🇿 🇵🇸3 years ago

State updates are asynchronous

harpaljadeja.eth (evm/acc) 🇮🇳's profile picture
harpaljadeja.eth (evm/acc) 🇮🇳3 years ago

So what's the solution?

🦭x's profile picture
🦭x3 years ago

Closure

Eberechi's profile picture
Eberechi3 years ago

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.

nadim's profile picture
nadim3 years ago

What are you using to create this awesome code animation?

Claudio's profile picture
Claudio3 years ago

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

Related Videos