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 anunsubscribefunction.
- On creation, dispatch an internal
combineReducers({ key: reducer, … })builds one reducer from several slice reducers.useSelector(store, selector)returnsselector(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 aTypeError. - Reducers may not dispatch: calling
dispatchwhile a reducer runs throws anError. - A listener that unsubscribes (or subscribes) during a dispatch does not change who is notified for that dispatch.
combineReducersreturns 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.
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.