I'm currently learning how React works under the hood and built a custom useState from scratch following the tutorials on Youtube. But I'm having trouble understanding how callIndex is incremented and why do I need to set currentIndex variables which basically take the callIndex value.
The code works like this -
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
let callIndex = -1;
let stateValues = [];
const useState = (initValue) => {
callIndex++;
console.log("callIndex", callIndex);
const currentIdx = Number(callIndex);
if (stateValues[currentIdx] === undefined) {
stateValues[currentIdx] = initValue;
}
const setState = (newValue) => {
console.log("currentIdx in setState", currentIdx);
stateValues[callIndex] = newValue;
render();
};
return [stateValues[currentIdx], setState];
};
const App = () => {
const [countA, setCountA] = useState(1);
const [countB, setCountB] = useState(-1);
const [countC, setCountC] = useState(0);
return (
<div>
<div>
<h1>Count A: {countA}</h1>
<button onClick={() => setCountA(countA - 1)}>Subtract</button>
<button onClick={() => setCountA(countA + 1)}>Add</button>
</div>
<div>
<h1>Count B: {countB}</h1>
<button onClick={() => setCountB(countB - 1)}>Subtract</button>
<button onClick={() => setCountB(countB + 1)}>Add</button>
</div>
<div>
<h1>Count C: {countC}</h1>
<button onClick={() => setCountC(countC - 1)}>Subtract</button>
<button onClick={() => setCountC(countC + 1)}>Add</button>
</div>
</div>
);
};
function render() {
// callIndex = -1;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
}
render();
Every time the useState function is called, the callIndex variables would be incremented by 1. In this code, I called useState 3 times. So, the callIndex value would be 3.
The problem starts here - when I called the setState function, it'll first assign the newValue to the stateValues but in which index will it be changed.
Are there any articles or tutorials explaining how this happening?