3 ms·
That's wrong, it's calling setAge immediately and not making a callback. You'll get an infinite render loop from that. It should be: const handleAgeChange =
by Izkata 1y ago
That's wrong, it's calling setAge immediately and not making a callback. You'll get an infinite render loop from that. It should be:
const handleAgeChange = () => setAge((prevAge) => prevAge + 1);
https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state https://react.dev/reference/react/useState#updating-state-ba...
The callback version is really only needed if there's a risk of setAge being called multiple times between renders and you do actually want all the mutations, vs only wanting it based on what's currently rendered.
- ascagnel_ 1y agoAh this is what I get for trying to write code on my phone. I'm specifically thinking of cases within useEffects, where the state setter is constant between renders but the state itself is not, so you can wind up with an infinite re-render once the state has changed once, unless you check the state inside the useEffect before calling setState.