Skip navigation
"Why can't I access an updated state value in React immediately?"
0:00 / 0:27

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

Alex Sidorenko

@asidorenko_35K followers

Visit on X
938 likesDownloadOriginal post

142,252 views

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

9 Comments

Comments from the original post on X (Twitter)

  • Alex Sidorenko's profile picture

    @asidorenko_

    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.

    53 likes

  • Shyam Makwana's profile picture

    @Technoknol

    Other solution is to use callback function like:

    25 likes

  • Neo 🍍🍍's profile picture

    @PineapplesDev

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

    10 likes

  • Bilal Tamerhoulet 🇩🇿 🇵🇸's profile picture

    @BTamerhoulet

    State updates are asynchronous

    7 likes

  • harpaljadeja.eth (evm/acc) 🇮🇳's profile picture

    @HarpalJadeja11

    So what's the solution?

    3 likes

  • 🦭x's profile picture

    @Babloo_o_

    Closure

    3 likes

  • Eberechi's profile picture

    @EberechiUche1

    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.

    3 likes

  • nadim's profile picture

    @nadim_hallaq

    What are you using to create this awesome code animation?

    2 likes

  • Claudio's profile picture

    @kazzkiq

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

    2 likes