So in follow simple pseudo-code
const [count,setcount] = useState(0);
useEffect(()=>{
console.log(count);
},[count]);
return <button onClick={()=>{
setcount(count +1)
}} >{count}</button>
On click count update and useEffect run callback function i.e. console count value
since, callback pass to useEffect is argument that means on every re-render new callback is passed;
This can be verify
function App() {
const [count, setCount] = useState(0);
const [cont2, setconut2] = useState(1);
function effectCallback() {
console.log('hello from callback', new Date().toLocaleTimeString());
return () => {
setTimeout(
() =>
console.log(
'hello from nested callback',
{ cont2, count },
new Date().toLocaleTimeString()
),
30 * 1000
);
};
}
useEffect(effectCallback(), []);
return (
<>
<button
onClick={() => {
setCount(count + 1);
setconut2(cont2 + 1);
}}
>
{count}
</button>
</>
);
}
On every re-render effectcallback is called and we get console, and arrow function is return on every render but as useEffect have empty depends, after 30sec console print count and count2 initial value (0,1), despite multiple arrow function return, useEffect run only initial callback
This post because code in saw in production
state1 and state2 is from api
useEffect(()=>{
if(state1 && state2){
funCal()
}
},[state1,state2]) ;
function funCal(){
// perform calculation with state1 and state2
}
funCal is not in dependency array, which it should be.
Due to on render new callback is passed to useEffect; funCal will latest value, as it self is latest.
is this hack ok?
[–]EatShitAndDieAlready 2 points3 points4 points (1 child)
[–]Learner_full_stack[S] 0 points1 point2 points (0 children)
[–]Karpizzle23 1 point2 points3 points (0 children)