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)
- Each component instance has an array of hook slots.
- During render, a cursor starts at 0; each
useStatecall reads slotcursor++. This is why hooks must be called in the same order every render: no hooks inside conditions or loops. - The setter writes to its slot and schedules a re-render.
- Batching: several setter calls in the same tick cause a single render, scheduled as a microtask.
- Setters accept a value or an updater function (
set(c => c + 1)), which avoids stale values when updating several times in a row. - 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
1function createRoot(Component, onRender) {2 const hooks = []; // state slots for this component instance3 let cursor = 0;4 let scheduled = false;5 const effects = [];67 function render() {8 scheduled = false;9 cursor = 0; // hooks are matched by call order10 const output = Component();11 onRender(output);12 effects.splice(0).forEach((run) => run()); // run effects after rendering13 }1415 function scheduleRender() {16 if (scheduled) return; // batch several updates into one render17 scheduled = true;18 queueMicrotask(render);19 }2021 function useState(initial) {22 const i = cursor++;23 if (!(i in hooks)) hooks[i] = typeof initial === "function" ? initial() : initial; // lazy init24 const setState = (next) => {25 const value = typeof next === "function" ? next(hooks[i]) : next;26 if (Object.is(value, hooks[i])) return; // bail out: nothing changed27 hooks[i] = value;28 scheduleRender();29 };30 return [hooks[i], setState];31 }3233 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 }4445 return { render, useState, useEffect };46}4748// A "component" using the hooks49const renders = [];50const root = createRoot(Counter, (ui) => renders.push(ui));51const { useState, useEffect } = root;52let api;5354function 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}6465root.render(); // initial render66api.increment();67api.increment();68api.increment(); // three updates in one tick...69await Promise.resolve(); // ...one batched render70api.setSame(); // same value: no render71await 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.