DEV Community

Discussion on: We don't know how React state hook works

kosich profile image
Kostia Palchyk • Edited

Thank you, Adam! I've learned something new!

BTW, tried this in a REPL:
Theres seem to be an anomaly when the state is updated for the first time: it calculates first updater immediately. All consequent updates work as you describe! Probably another optimization, don't want to dig sources for that 😢🙂

Again, thanks!

UPD: That's the eager computation, see Adam's comment 👇

(P.S: theres a typo in "beind")

adamklein profile image
adam klein Author

glad you learned something :)

That's the eager computation.

I think React tries to optimize based on the prediciton that the previous outcome will repeat itself.
So if the last time the state changed, it will start with lazy computation. But if the last time the state didn't change - it will start from eager computation. But that's just my guess, I haven't seen that in the code and I honestly have no idea.

I tried to demonstrate it here (forked your stackblitz):

kosich profile image
Kostia Palchyk • Edited

Right you are! Thanks and sorry, missed that one while reading first time.