I am trying to understand how to implement useState hook using pure Javascript. and I stuck at the part where the closure is used.
here is the code.
const React = (function () {
let hooks = [];
let idx = 0;
function useState(initVal) {
const _idx = idx;
console.log(_idx) // 0, 1
const state = hooks[idx] || initVal;
const setState = newVal => {
hooks[_idx] = newVal;
};
idx++;
return [state, setState];
}
function render(Component) {
idx = 0;
const C = Component();
C.render();
return C;
}
return { useState, render };
})();
function Component() {
const [count, setCount] = React.useState(1);
const [text, setText] = React.useState('apple');
return {
render: () => console.log({ count, text }),
click: () => setCount(count + 1),
type: (word) => setText(word),
}
}
var App = React.render(Component); // {count: 1, text: "apple"}
App.click();
var App = React.render(Component); // {count: 2, text: "apple"}
App.type('pear');
var App = React.render(Component); // {count: 2, text: "pear"}
When setState function(click or type) is called, it updates value of hooks array according to their index which is 0 for count and 1 for text.
Which means setState function inside useState remembers the value of _idx of each state(count and text) by javascript closure?