I try to add a feature to my simple Counter (React) App which alerts when counter reaches 0 onClick increase or decrease button. But alert always late for 1 click. How can I fix it?
Here is my code:
function App() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter((oldState) => oldState + 1);
if (counter === 0) alert('it is 0');
}
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>
);
}
I want to see alert exactly when I see 0 on the screen. But the code above shown alert only after the counter passed zero.
>Solution :
This is happening bcoz setCounter is async operation.
We can fix this using this two ways
-
wrap alert function inside the setCounter’s callback.
function handleIncrement() {
setCounter((oldState) => {
if (oldState + 1 === 0) { alert('it is'); } return oldState + 1;});
}
function handleDecrement() {
setCounter((oldState) => {
if (oldState - 1 === 0) { alert('it is'); } return oldState - 1;});
}
-
you can also use useEffect to achieve this
useEffect(() => {
if (counter === 0) { alert('it is'); }}, [counter]);
function handleIncrement() {
setCounter(counter + 1);}
function handleDecrement() {
setCounter(counter - 1);}