Lil clarification regarding useState

Hi, in functional component the entire function re-runs when a piece of state changes, right? How come the previous piece-of-state value is remembered when the entire function, not a section of the function, is being run over and over again? Is it stored somewhere by React?
Thank you.

Right. This is a good question. I don’t know the inner workings, but I’m told that it uses a closure to retain the value between runs. You can find discussions of this online and attempts to reverse engineer it, if you’re so inclined.

But yeah, it’s a fair question. I scratched my head over that, too. But they’re smart guys and gals over at Facebook - they have it taken care of.

1 Like

I don’t know if this fully answer your question, but there’s a small section in the documentation:

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState() , it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one.

1 Like

Okay, I’d overlook it. Thanks so much @kevinSmith @Marmiz!