I am new to react and this is a very simple counter that increments value by 5, I learnt that useEffect is executed after every component re-render/dependency variable change. But I found that useEffect (i.e alert) is appearing before the value in the h1 changes
import { useEffect, useState } from "react";
export default function App() {
const [number, setNumber] = useState(0);
let prev = 0;
useEffect(() => {
if (number !== 0) {
alert("Number changed to " + number);
}
}, [prev, number]);
console.log(prev);
return (
<>
<h1>{number}</h1>
<button
onClick={() => {
setNumber((n) => {
prev = n;
return n + 5;
});
}}>
+5
</button>
</>
);
}
Expected Outcome: alert happens after h1 value increments by 5
Current Result: alert comes first and h1 value increments after closing the alert
2
Answers
useEffect runs basically like componentDidMount,
so it runs first time after the component mounted and then after every re-render
This is when useEffect runs:
Therefore, in your case, it runs when the component is rendered for the first time, when the number changes, and when the prev changes. Also, do not change prev the way you are doing it right now, it will cause an infinite loop!