FrontendPro

64Implement a small Redux-style store using subscriptions and reducers

mediumAbout 35 minutesCodingreactstate-managementpub-subuseSyncExternalStore

Problem

Implement the core of Redux and a React binding:

  • createStore(reducer, preloadedState) returns { getState, dispatch, subscribe }.
    • On creation, dispatch an internal { type: "@@INIT" } action so reducers can supply their default state.
    • dispatch(action) runs the reducer, stores the new state, calls every subscriber, and returns the action.
    • subscribe(listener) returns an unsubscribe function.
  • combineReducers({ key: reducer, … }) builds one reducer from several slice reducers.
  • useSelector(store, selector) returns selector(store.getState()) and re-renders the component only when that selected value changes.
const store = createStore(combineReducers({ todos, filter }));
function Count() {
  const count = useSelector(store, (state) => state.todos.length);
  return <span>{count}</span>; // does not re-render when only the filter changes
}
store.dispatch({ type: "todos/add", text: "Ship it" });

Requirements

  • Actions must be plain objects with a string type; otherwise throw a TypeError.
  • Reducers may not dispatch: calling dispatch while a reducer runs throws an Error.
  • A listener that unsubscribes (or subscribes) during a dispatch does not change who is notified for that dispatch.
  • combineReducers returns the same state object when no slice changed.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

Build Your Own Redux | Part 2 | CreateStore API | Advanced JavaScript | Devtools TechDevtools Tech on YouTubeOpen on YouTube

Step-by-step

createStore holds state, the reducer and a list of listeners in local variables. Only getState, dispatch and subscribe can reach them.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever