React Docs says:
How does React associate Hook calls with components?
React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components). 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. This is how multiple useState() calls each get independent local state.
First of all... what is this "memory cell"? Can we print it out ourselves to see its value?
Second, there is only one instance of the function (such as Counter()
in the following example). So if we render <Counter />
twice into the DOM, once to <div id="root1">
and the second time to <div id="root2">
, how does the function Counter()
know which is which?
function Counter() {
let [count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}> + </button>
{ count }
<button onClick={() => setCount(count - 1)}> - </button>
</div>
)
}