Skip to the solution
MediumLow-Level Design7 min read

Build a Minimal createStore() (Redux-Lite: dispatch, subscribe, reducers)

1.1k views

The problem

Problem, as an interviewer would state it: "Implement a minimal createStore(reducer, initialState) — like Redux — with getState(), dispatch(action), and subscribe(listener)."

Examples:

Code
const store = createStore(counterReducer, { count: 0 });
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: "INCREMENT" }); // logs { count: 1 }

Clarifying questions expected:

  • Should subscribe return an unsubscribe function, and must calling it correctly stop future notifications for JUST that listener?
  • Should the reducer receive the CURRENT state and an action, returning a brand-new state (never mutating), matching the real, standard Redux convention?
  • Should dispatch itself return anything meaningful, like the action that was dispatched?

Code / implementation expected: Yes — real, direct proof of a real dispatch sequence, confirming correct state updates, subscriber notification on every dispatch, and a correctly-working unsubscribe.

  • state-management
  • system-design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: dispatch correctly updates state and notifies subscribers, and unsubscribe genuinely stops further notifications for that listener

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 81 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement EventEmitter (on/off/once/emit) — Node style

Continue