recently i came around this problem statement, where i needed to tell the value that will be printed on the button for the below react code.
export function App() {
const [count1, setCount1] = useState(1);
const [count2, setCount2] = useState(count1 + 1);
console.log('count1 :', count1);
console.log('count2 :', count2);
useEffect(() => {
setCount2((prev) => prev + count1);
}, [count1])
return (
<button onClick={() => {
setCount1(count2 + 1)
}}>
{count2 / count1}
</button>
);
}
my initial guess was that the value of count2 will be 2 and the value printed on the button will be 2/1 > 2. But on running it locally, i got to know that the answer was 4.
can someone explain to me why the value of count2 becomes 4?
New contributor
2Dfax is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.