All visualizationsReact · 11 of 18
useState, built from scratch — where state REALLY lives
Your component is a function that forgets everything. Build React’s memory shelf in 15 runnable lines and watch a click survive a re-render.
💡
THE BIG IDEA
Every React beginner meets the same ghosts: "why does console.log show the old state?", "why can’t hooks go inside if?", "why is my initial value ignored?" All three are the SAME fact wearing different masks — state lives outside your function, found again each render by call order. Instead of memorising the rules, we build useState ourselves and watch the ghosts turn into machinery.
Move your mouse over any line to see what it does. Hover a loop line and it plays through every repeat. Or press ▶ Play to watch the whole thing. On a phone, tap the arrows.
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
1/17
UP NEXT IN REACT
Props down, events up — the one-way street (and the 12-lesson recap)
The Button displays what it’s given and rings the bell it was handed — ownership never moves. Then the whole vertical, in one breath.
React.memo vs === — equal content, different identityProps down, events up — the one-way street (and the 12-lesson recap)