Skip to content

OutputNot attempted

How closures power React hooks

const React = (function () {
let hooks = [];
let current = 0;
return {
render(Component) {
const c = Component();
current = 0;
return c;
},
useState(initial) {
const i = current;
if (hooks[i] === undefined) hooks[i] = initial;
const set = (v) => { hooks[i] = v; };
current++;
return [hooks[i], set];
},
};
})();
function Counter() {
const [count, setCount] = React.useState(0);
const [text, setText] = React.useState('apple');
return { click: () => setCount(count + 1), type: setText, show: () => console.log(count, text) };
}
let App = React.render(Counter);
App.show();
App.click();
App = React.render(Counter);
App.show();
App.type('banana');
App.click();
App = React.render(Counter);
App.show();

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

State lives in the hooks array inside the closure, indexed by CALL ORDER (that's why hooks can't be conditional). Each setter closes over its own index. The second click uses the count captured during the second render (1), so it sets 2, not 3.