Build a mini React-like state system

A mini React-style state system needs a component function that re-runs to produce UI, a useState hook whose values live outside the function in a per-component array indexed by call order, and setters that update the value and schedule a re-render, ideally batched in a microtask.

How React's hooks really work (simplified)

  1. Each component instance has an array of hook slots.
  2. During render, a cursor starts at 0; each useState call reads slot cursor++. This is why hooks must be called in the same order every render: no hooks inside conditions or loops.
  3. The setter writes to its slot and schedules a re-render.
  4. Batching: several setter calls in the same tick cause a single render, scheduled as a microtask.
  5. Setters accept a value or an updater function (set(c => c + 1)), which avoids stale values when updating several times in a row.
  6. Bail out if the new value is identical (Object.is) to the old one.

Adding useEffect

Store effect callbacks and their dependency arrays in slots; after rendering, run effects whose dependencies changed, calling the previous cleanup first.

What the real React adds

A fiber tree per component, reconciliation (diffing the new UI against the old), priorities and concurrent rendering, transitions, Suspense, context, server components, and the React Compiler's automatic memoisation. But the core idea of hooks is exactly this ordered slot list.

Why this is a great interview question

It tests closures, render scheduling, microtasks, and the rules of hooks, and shows you understand what React does rather than only how to use it.

Code example

js
1function createRoot(Component, onRender) {
2 const hooks = []; // state slots for this component instance
3 let cursor = 0;
4 let scheduled = false;
5 const effects = [];
6
7 function render() {
8 scheduled = false;
9 cursor = 0; // hooks are matched by call order
10 const output = Component();
11 onRender(output);
12 effects.splice(0).forEach((run) => run()); // run effects after rendering
13 }
14
15 function scheduleRender() {
16 if (scheduled) return; // batch several updates into one render
17 scheduled = true;
18 queueMicrotask(render);
19 }
20
21 function useState(initial) {
22 const i = cursor++;
23 if (!(i in hooks)) hooks[i] = typeof initial === "function" ? initial() : initial; // lazy init
24 const setState = (next) => {
25 const value = typeof next === "function" ? next(hooks[i]) : next;
26 if (Object.is(value, hooks[i])) return; // bail out: nothing changed
27 hooks[i] = value;
28 scheduleRender();
29 };
30 return [hooks[i], setState];
31 }
32
33 function useEffect(callback, deps) {
34 const i = cursor++;
35 const prev = hooks[i];
36 const changed = !prev || !deps || deps.some((d, k) => !Object.is(d, prev.deps[k]));
37 if (changed) {
38 effects.push(() => {
39 prev?.cleanup?.();
40 hooks[i] = { deps, cleanup: callback() };
41 });
42 }
43 }
44
45 return { render, useState, useEffect };
46}
47
48// A "component" using the hooks
49const renders = [];
50const root = createRoot(Counter, (ui) => renders.push(ui));
51const { useState, useEffect } = root;
52let api;
53
54function Counter() {
55 const [count, setCount] = useState(0);
56 const [label] = useState(() => "Clicks");
57 useEffect(() => {
58 renders.push(`effect: count is ${count}`);
59 return () => renders.push(`cleanup for ${count}`);
60 }, [count]);
61 api = { increment: () => setCount((c) => c + 1), setSame: () => setCount(count) };
62 return `${label}: ${count}`;
63}
64
65root.render(); // initial render
66api.increment();
67api.increment();
68api.increment(); // three updates in one tick...
69await Promise.resolve(); // ...one batched render
70api.setSame(); // same value: no render
71await Promise.resolve();
72console.log(renders);
73// ["Clicks: 0", "effect: count is 0", "Clicks: 3", "cleanup for 0", "effect: count is 3"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app