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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With