Give the codes below
import { useState } from "react";
import "./styles.css";
export default function App() {
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
const inc1 = () => {
console.log("debug inc:", count1);
setCount1((prev) => prev + 1);
};
const inc2 = () => {
console.log("debug inc2:", count2);
setCount2(count2 + 1);
};
const [processInc1] = useState(() => {
console.log("debug longProcessBeforeInc:", count1);
// Run some long process here
return inc1;
});
const [processInc2] = useState(() => {
console.log("debug longProcessBeforeInc:", count2);
// Run some long process here
return inc2;
});
console.log("debug render:", count1, count2);
return (
<div className="App">
<h3>
{count1} - {count2}
</h3>
<button onClick={inc1}>Inc 1</button>
<br />
<br />
<button onClick={inc2}>Inc 2</button>
<br />
<br />
<button onClick={processInc1}>Long Inc 1</button>
<br />
<br />
<button onClick={processInc2}>Long Inc 2</button>
</div>
);
}
inc1, inc2, processInc1 all works as expected where you increase value by 1 and it renders correctly.
So with inc1, inc2 the main difference is setCount1((prev) => prev + 1); and setCount2(count2 + 1);, and processInc1, processInc2 basically return inc1 and inc2 respectively via useState first time the component renders.
I understand from here https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function that it has something to do with closure but given the example above I fail to wrap my head around why inc2, and processInc1 works but not processInc2?
Here is the link to the codesandbox for the above
https://codesandbox.io/s/eloquent-morse-37xyoy?file=/src/App.js