0
const [ready, set_ready] = useState(false);

...

if (condition === true) {
  set_ready(true);
}

The code above causes infinite loop.

But if I changed it to

if (condition === true && !ready) {
  set_ready(true);
}

The the problem is fixed.

This means that setting the ready useState to its current value triggers re-render.

This does not make sense.

Can anyone explain?

1 Answers1

1

When a state setter is called, it does two things:

  • Updates React's internal state for that state variable
  • Re-renders the component. In functional components, this will call the component function again, and the various useState calls return the updated internal state.

So if you unconditionally call a state setter in the main body of a functional component, you'll be triggering a re-render every time the function runs - and a re-render will result in the function being called again, hence the infinite loop.

Putting the state setter call inside a condition ensures that it only gets called when it needs to, rather than on every single render.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320