that's okay, because react renders in frames like when you watch a movie or play a video game, at the current frame where you call this line
setCounter((oldState) => oldState - 1);
counter
still 1
not 0
, so you need to wait until react do the re-render, then the next render start with counter
being 0
, but the alert you defined inside click handler won't be called automatically, you didn't call it, you made that call inside the onClick
handler which will not be called until button clicked(obviously)
so the problem is not with how react re-render the state, it's where to put your alert
or in other words how to consume your state
a simple fix to your solution is to put alert
outside the call, in the component body
function App() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter((oldState) => oldState + 1);
}
function handleDecrement() {
setCounter((oldState) => oldState - 1);
}
if (counter === 0) alert('it is 0');
return (
<div>
<button onClick={handleIncrement}>increment</button>
<div>{counter}</div>
<button onClick={handleDecrement}>decrement</button>
</div>
);
}
Anyway it's not a good idea to have alert
called inside the body of a component so I'd assume you have an alert component that's shown to the user when the counter reach 0
function App() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter((oldState) => oldState + 1);
}
function handleDecrement() {
setCounter((oldState) => oldState - 1);
}
if(counter == 0){
return <Alert message="counter is 0 now"/>
}
return (
<div>
<button onClick={handleIncrement}>increment</button>
<div>{counter}</div>
<button onClick={handleDecrement}>decrement</button>
</div>
);
}