Reputation: 1796
I am working with webpack and react. I create count increment in my application, but when i click on button state not changed, But when i click again than count increment or you can say state updated. Please check my code below and let me know where i am wrong.
You can check in below image i clicked twice but count is 1.
import React, { useState } from "react";
const Count = () => {
let [count, setCount] = useState(0);
function click() {
console.log("clicked");
setCount(count++);
}
return (
<div>
<button onClick={click} className="btn btn-primary">
Click here
</button>
<h3>{count}</h3>
</div>
);
};
export default Count;
Any solution appreciated!
Upvotes: 4
Views: 3657
Reputation: 9769
Use previous state
function click() {
console.log("clicked");
setCount(prevCount => prevCount+1);
//or
//setCount(count+1);
}
Upvotes: 1
Reputation: 454
ok you have one of three solutions:
setCount(prevState => prevState +1)
setCount(++count)
setCount(count + 1)
your code does not work because you are using a post-increment operation, which uses the value then increment 1 to it which caused the confusion you are currently facing.
Upvotes: 7
Reputation: 464
counter++
is post incremental and it uses the count value first and then plus 1 to it. so, first time you click on the button, it sets count with count
and then add 1 to it. to use pre incremental ++count
or count + 1
instead of count++
Upvotes: 1
Reputation: 4591
In React, state update is asynchronous.
You should write:
setCount(previousCount => previousCount + 1);
To learn more: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Upvotes: 3