I am currently working on my understanding of the useState hook from react.
What I would like to know is; when useState is called how is it able to correctly retrieve the state object and the function that can be used to modify it, for that specific functional component (assuming it has already been created the first time it was called.)
Another way to phrase my question would be where does count and setCount exist? useState() will obviously return a different state object and modifier function depending on which functional component useState is called in, so how does that work?
My guess would be that a closure is formed which means that this functional component has a lexical environment which consists of any local variables that were in-scope at the time the closure was created and this is what makes count and setCount available when useState is called. But I haven't been able to confirm this and since react is involved I could be way off.
export const MyFunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<h1>This is my component.</h1>
);
}
Can anyone clear this up for me?
@edit: I'm pretty sure I'm way off with my thinking about closures, looking at the react library source code I found the implementation for the useState function.
export function useState<S>(initialState: (() => S) | S) {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
I'm probably going to have to dig in and unpack this to get an answer.