understanding weird setState behaviour in reactjs using useState hooks

const[count,setcount]=useState(0)
function inc() {
setcount(count + 5);
setcount(count + 5);
setcount(count + 5);
setcount(count + 5);
}
return (
<div>
  <h1>{count}</h1> #output =5
  <button onClick={() => inc()}>clickme</button>
</div>
);




}
function inc() {
setcount(count=>count + 5);
setcount(count=>count + 5);
setcount(count=>count + 5);
setcount(count=>count + 5);
}
return (
<div>
  <h1>{count}</h1> #output =5
  <button onClick={() => inc()}>clickme</button>
</div>
);
}

When i call the first function on button click count value become 5 while in second function it becomes 20. I am unable why is this behaviour



Read more here: https://stackoverflow.com/questions/64899105/understanding-weird-setstate-behaviour-in-reactjs-using-usestate-hooks

Content Attribution

This content was originally published by Fazal Ur Rehman Fazal at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: