2

According to the official React docs on useState,

If the initial state [to be passed to useState] is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render

My question: I thought that the expression [myState, setMyState] = useState('starting value') was always only executed on initial render; if it were executed more than once, wouldn't that set the value of myState back to starting value?

I don't see why lazy initialization is needed unless useState get called more than once, and doing that seems to undermine the idea of preserving state between renders.

Thanks!

r_zelazny
  • 517
  • 3
  • 19
  • yes, it does - the author states that "even though the initial value is disregarded upon next renders, the function which initializes it still gets called". Not sure why the function gets called if the value is going to be discarded, but it does make sense. Thanks! – r_zelazny Feb 05 '21 at 21:43

0 Answers0