Say you have something like this:
const MyComponent = (props) => {
const refA = React.useRef()
const refB = React.useRef()
const refC = React.useRef()
const [x, setX] = React.useState(true)
const [y, setY] = React.useState([])
return <div>...</div>
}
In pseudocode, what is this actually doing when it is called multiple times? Are they doing this basically?
- Know that
MyComponent
is about to be converted from the function into a virtual tree. - Set a global variable that's going to track when every
useX
hook is called within a single procedural frame. - Store for this component instance the outputs from each of these hook calls.
- The next time the hooks are called for this component ID, it gets the map of the last returned results from the last
useX
calls from within this component.
I ask because (a) it seems like it can only be done with a global variable trick of some sort, and (b), the corresponding code is quite complicated and difficult to parse.
Wondering if one could just give a quick high-level overview or some pseudocode on how React implements these magical hooks.
It seems like it's something like this, though more advanced:
let dispatcher = {}
function MyComponent() {
}
function begin() {
dispatcher.component = {
refs: [],
states: []
}
}
function useRef() {
let ref = {}
dispatcher.component.refs.push(ref)
return ref
}
function useState(val) {
let state = val
dispatcher.component.states.push(val)
return state
}
function end() {
dispatcher.component = null
}
I just don't see how it can memoize and such with this magic.
This is not the same as the question as knowing how hooks know which component they are for. That is just one aspect to my question, I am asking generally how the hooks work.