DEV Community

Discussion on: React useState hook is asynchronous!

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 Author

Yeah! I will definitely try it...