All visualizationsReact · 4 of 18
Custom hooks — a recipe, never a shared pot
Build useToggle on the mini-useState shelf, call it twice, flip one — and prove the other never moves.
💡
THE BIG IDEA
Custom hooks look like magic until you watch one run: useToggle is a plain function that calls useState and hands back something friendlier. The famous fear — "if two places use my hook, do they share state?" — is answered by execution: two calls take two shelf slots, flipping dark mode leaves sound untouched, and the program prints it.
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(init) {
3 const i = cursor++;
4 if (box[i] === undefined) box[i] = init;
5 return [box[i], (v) => { box[i] = v; }];
6}
7function useToggle(init) {
8 const [on, setOn] = useState(init);
9 return [on, () => setOn(!on)];
10}
11function App() {
12 cursor = 0;
13 const [dark, flipDark] = useToggle(false);
14 const [sound, flipSound] = useToggle(true);
15 console.log("dark:", dark, "| sound:", sound);
16 return [flipDark, flipSound];
17}
18const [flipDark] = App();
19flipDark();
20App();
Every tutorial says "extract a custom hook!" and every beginner wonders: do I register it somewhere? Is the use- prefix magic? And if two components use my hook… do they share the state?
Three questions, one execution. We reuse the mini-useState shelf from lesson 1, build useToggle on top of it, use it TWICE — and flip only 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/9
UP NEXT IN REACT
The fetch race — when the wrong results win
Two requests, one screen: watch the stale response overwrite the fresh one, then fix it with a one-integer ticket check.
Controlled inputs — one memory, or a form that liesThe fetch race — when the wrong results win