Languages

React - useState set method does not reflecting my change immediately

5 points
Asked by:
Jun-L
963

Hi there!

What is the problem with my component? When I try to set state, and use it again the state doesn't reflect previous change. What is wrong with my code?

Why component dysplays proper result on my site, and console logs wrong result value?

1 answer
7 points
Answered by:
Root-ssh
178290

useState setter schedules update action that will be visible in the next rendering cycle.

useState set operation is `asynchronous` and will not be reflected immediately.

You can try to use the following source code to see the result change effect:

second useEffect() will be triggered always on result changed, and after the component will be mount/ready.

Alternative solutions

1. Helper newResult variable/constant:

1. Setter with callback: 

0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join