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?
Which means setState function inside useState remembers the value of _idx of each state(count and text) by javascript closure?
Yes. When useState is called, it gets the next available index using idx and stores it in the constant _idx. The setState function returned forms a closure because of which it remembers the _idx corresponding to its state even though useState has finished execution.
I stuck at the part where the closure is used.
Other places where closure is used:
useState and render functions inside the React module form a closure over hooks and idx. Hence the functions are able to read/write to these variables even after React (an iife) has finished execution.render, click and type functions form a closure.
The render method closes over Component. Hence it is able to access count and text even after Component function has finished execution.
Similarly, click and type form a closure and hence can invoke setCount and setText funtions which were defined inside Component scope.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With