I use a very simple example to check my understanding of how state works. Below is a simple calculator with initial value 1.
When I press the button , the console shows "Run" and the calculator shows "2". When I press the button again, the console still outputs "Run" and the calculator shows "2". When I continue to press , console does not output anything.
import {useState} from "react";
const App = () => {
console.log("Run")
const [counter, setCounter] = useState(1);
console.log(counter)
const addHandler = () => {
setCounter(2);
};
const subtractHandler = () => {
setCounter(counter - 1);
};
return <div className="app">
<h1>{counter}</h1>
<button onClick={addHandler}> </button>
<button onClick={subtractHandler}>-</button>
</div>
};
export default App;
The second output is confusing me, because my understanding is that state will re-render the function when the state variable "counter" changes. However, after the first press, the counter is already set to be "2". When the button was pressed one more time, why console still outputs "Run" and "2"?
CodePudding user response:
Your addHandler
assigned to your buttons onClick
event is not incrementing your counter
value but rather always assigning the value 2
.
const addHandler = () => {
setCounter(2); // always setting the value of counter to 2
}
What you likely want is to access the previous state value of counter
and increment its value:
const addHandler = () => {
setCounter(value => value 1);
}
CodePudding user response:
Use console.log("Run") inside the addHanlder function,in this way console log will work on every time the addHandler function will be called and set the counter state like this:
const addHandler = () => {
console.log("Run")
setCounter(counter 1);
};