DEV Community

Discussion on: React useState hook is asynchronous!

Collapse
 
noyan profile image
noyan • Edited

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...

Collapse
 
jiwei_he_de51ab3542e8df9d profile image
Jiwei He • Edited

I modified your code to make it work in the expected way:

codesandbox.io/s/red-field-isi29y?...

Collapse
 
oreakinwole profile image
Ore Akinwole

This is really good

Collapse
 
shareef profile image
Mohammed Nadeem Shareef • Edited

Yeah! absolutely correct... and that's why I use two diffrent states

my scenario was


setState(state); // Update some state
doSomething(); // Do something with the state

Enter fullscreen mode Exit fullscreen mode

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 state
useEffect(() => {
    doSomething(state) // do something with the updated state.
},[state]) // This will call again when the state is updated
Enter fullscreen mode Exit fullscreen mode
Collapse
 
noyan profile image
noyan

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.

const Func = () => {
  const [count, setCount] = useState(0);    // initially count = 0 (When it was first mounted)
  const handleClick = () => {
    setCount(prev => prev + 1);                 // count = 1 
    setCount(prev => prev + 1);                 // count = 2
  }

  return (
    <button onClick={handleClick}>{count}</button>
)
}
Enter fullscreen mode Exit fullscreen mode

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...

Thread Thread
 
shareef profile image
Mohammed Nadeem Shareef

Yeah! I will definitely try it...