1const box = []; let cursor = 0;
2function useState(initial) {
3 const i = cursor++;
4 if (box[i] === undefined) box[i] = initial;
5 return [box[i], (v) => { box[i] = v; render(); }];
6}
7function Counter() {
8 const [count, setCount] = useState(0);
9 console.log("screen: count =", count);
10 return setCount;
11}
12function render() { cursor = 0; return Counter(); }
13const onClick = render();
14onClick(5);
15onClick(9);
●You clicked +1 and the number on screen changed. But a React component is JUST A FUNCTION — and a function forgets everything when it ends. So where does count live?
We answer by building useState ourselves, in 15 lines that really run. This miniature is honest: real React batches updates and schedules renders, but the ownership trick is exactly this one.
📦 Memory boxes
what the program is remembering right now
nothing remembered yet🖥️ What the computer shows
the answers the program prints out
nothing yet ▌