Загрузка видео...

Не удалось загрузить видео

На главную

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

142,247 просмотров • 3 лет назад •via X (Twitter)

Комментарии: 9

Фото профиля Alex Sidorenko
Alex Sidorenko3 лет назад

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
Shyam Makwana3 лет назад

Other solution is to use callback function like:

Фото профиля Neo 🍍🍍
Neo 🍍🍍3 лет назад

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

Фото профиля Bilal Tamerhoulet 🇩🇿 🇵🇸
Bilal Tamerhoulet 🇩🇿 🇵🇸3 лет назад

State updates are asynchronous

Фото профиля harpaljadeja.eth (evm/acc) 🇮🇳
harpaljadeja.eth (evm/acc) 🇮🇳3 лет назад

So what's the solution?

Фото профиля 🦭x
🦭x3 лет назад

Closure

Фото профиля Eberechi
Eberechi3 лет назад

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
nadim3 лет назад

What are you using to create this awesome code animation?

Фото профиля Claudio
Claudio3 лет назад

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

Похожие видео