In most cases you don't even need to make doubleCount a state. You can simply say const doubleCount = count * 2; and it'll just calculate it new when count updates. Sometimes, when you have a more complex setup, useEffect might come in handy though.
Though in the above example it may not seem to make sense, but maybe we are rendering a component based on the doubleCount(or any state which is dependent on another), then just the variable doubleCount doesn't help in rendering the component as it changes
Another (bit-tricky) way to solve this problem, is by setting the 'count' state with a callback, which returns an IIFE by itself, that will take the result of 'count' incremental as argument, sets doubleCount, and returns back the argument, which is the finally returned value for setCound.
Yeah! absolutely correct... and that's why I use two diffrent states
my scenario was
setState(state);// Update some statedoSomething();// Do something with the state
and I was not getting the updated state. as you can see in the example and two solve the I use useEffect.
setState(state);// Updates the stateuseEffect(()=>{doSomething(state)// do something with the updated state.},[state])// This will call again when the state is updated
I realized my comment was already included in your post. Sorry about that.
Actually, there is a simple way to write it without useEffect: setState(prev => prev + 1). It will update properly even if you update it multiple times in one render.
constFunc=()=>{const[count,setCount]=useState(0);// initially count = 0 (When it was first mounted)consthandleClick=()=>{setCount(prev=>prev+1);// count = 1 setCount(prev=>prev+1);// count = 2}return(<buttononClick={handleClick}>{count}</button> )}
It is called functional update. This one is easier to use or understand, and I recommend to use it when needed. reactjs.org/docs/hooks-reference.h...
Self-motivated front-end web developer having 2 years of experience workingon multiple projects. Extremely passionate to constantly develop my skills andgrow professionally.
So recently I learnt this the hard way too. But what I realized is if you await setCount call, although it doesnot return a promise, the following code will execute after the count has incremented. Hope it helps :)
"Great article! Understanding the asynchronous behavior of the useState hook in React is essential for writing efficient and effective code. While it can be easy to assume that the useState hook works synchronously like other functions, it's important to remember that React's state updates are batched and processed asynchronously for performance reasons.
The key takeaway from your article is that relying on the current value of state immediately after calling useState may not always return the most up-to-date value. Instead, you should use the callback function syntax to update state based on its previous value.
For those interested in learning more about React's useState hook, I recommend checking out this React usestate blog. Thanks for sharing your insights!"
In most cases you don't even need to make doubleCount a state.
You can simply say
const doubleCount = count * 2;
and it'll just calculate it new when count updates. Sometimes, when you have a more complex setup, useEffect might come in handy though.Thanks for the info man... π
Though in the above example it may not seem to make sense, but maybe we are rendering a component based on the doubleCount(or any state which is dependent on another), then just the variable doubleCount doesn't help in rendering the component as it changes
Another (bit-tricky) way to solve this problem, is by setting the 'count' state with a callback, which returns an IIFE by itself, that will take the result of 'count' incremental as argument, sets doubleCount, and returns back the argument, which is the finally returned value for setCound.
Another approach:- codesandbox.io/s/muddy-brook-iyzwk...
Hey man, thanks for the info.
Thanks! It was really helpful
Can I use async/ await too?
tbh
I don't know exactly may be you can or can't.
I would prefer not to use it.
Thanks for the writeup. Recently had to complete a project and ran into this issue. Now I at least know how to resolve it in future cases. π
π
Muchas gracias, fue muy util.
Thank you very much, it was very useful.
The doubleCount will be one step behind, because state is just a normal number in each call.
So, if you call setCount (count*2) after setCount(count+1), Counter displays 0 every time.
livedemo: codesandbox.io/s/vigorous-antonell...
see: overreacted.io/a-complete-guide-to...
Yeah! absolutely correct... and that's why I use two diffrent states
my scenario was
and I was not getting the updated state. as you can see in the example
and two solve the I use useEffect.
I realized my comment was already included in your post. Sorry about that.
Actually, there is a simple way to write it without
useEffect
:setState(prev => prev + 1)
. It will update properly even if you update it multiple times in one render.It is called functional update. This one is easier to use or understand, and I recommend to use it when needed.
reactjs.org/docs/hooks-reference.h...
Yeah! I will definitely try it...
I modified your code to make it work in the expected way:
codesandbox.io/s/red-field-isi29y?...
This is really good
Thanks for this article.
But I wanna add here useState is not async. It is actually sync.
why it doesn't update immediately because of the closure.
more on this here: youtube.com/watch?v=RAJD4KpX8LA
thanks :)
PS: i'm still learning it how it does work and how react render works under the hood.
Thanks for the input.
So recently I learnt this the hard way too. But what I realized is if you await setCount call, although it doesnot return a promise, the following code will execute after the count has incremented. Hope it helps :)
Thanks for the info. I would love to read the hard way. It might help many of us.
I came to the same solution, I I think this is why: developer.mozilla.org/en-US/docs/W...
"Great article! Understanding the asynchronous behavior of the useState hook in React is essential for writing efficient and effective code. While it can be easy to assume that the useState hook works synchronously like other functions, it's important to remember that React's state updates are batched and processed asynchronously for performance reasons.
The key takeaway from your article is that relying on the current value of state immediately after calling useState may not always return the most up-to-date value. Instead, you should use the callback function syntax to update state based on its previous value.
For those interested in learning more about React's useState hook, I recommend checking out this React usestate blog. Thanks for sharing your insights!"
Shareef Bacha
Very good, thank you!