Before your component is run, the renderer sets `_currentComponent` to your component with its hooks set to their current values.
If you run `useState(initial)` it looks like this:
function useState(initialValue) {
const component = _currentComponent
let hookValue;
if (firstRender) {
hookValue = {
hookName: 'useState',
value: [initialValue, (newValue) => {
hookValue[0] = newValue
markForUpdate(component); // some React-provided function to mark this as needing an update
}
}
component.hooks[component.currentHook++] = hookValue;
return hookValue.value
} else {
hookValue = component.hooks[component.currentHook++]
assert(hookValue.hookName == 'useState')
return hookValue.value
}
Surely not perfect, but totally useable as a model of what's going on. To be honest I wish React showed pseudocode like this in the tutorials, it makes it a lot easier for me to understand.
It might help to have a simple mental model for them?
Picture there is a global variable called _currentComponent:
Each HookValue is whatever that hook wants. For useState something like: Before your component is run, the renderer sets `_currentComponent` to your component with its hooks set to their current values.If you run `useState(initial)` it looks like this:
Surely not perfect, but totally useable as a model of what's going on. To be honest I wish React showed pseudocode like this in the tutorials, it makes it a lot easier for me to understand.