JS Built-ins
redux-legacycreateStoreadvanced

Store from Scratch

πŸ“– Usage Example
const store = createStore(reducer)

store.subscribe(() => console.log(store.getState()))

store.dispatch({ type: 'INCREMENT' }) // logs 1
store.dispatch({ type: 'INCREMENT' }) // logs 2

Implementing createStore from scratch shows how Redux manages state, subscriptions, and dispatch in only ~20 lines.

Store from Scratch

The Redux store is a plain object with three methods:

  • getState() β€” returns the current state
  • dispatch(action) β€” calls the reducer and notifies subscribers
  • subscribe(listener) β€” registers a callback; returns an unsubscribe function
function createStore(reducer) {
  var state = reducer(undefined, { type: '@@INIT' })
  var listeners = []
  return { getState, dispatch, subscribe }
}

Challenge: Implement createStore(reducer) with all three methods.

πŸ’‘ Hints (2)
  • β€’ Initialise state with `reducer(undefined, { type: '@@INIT' })` so reducers set their defaults.
  • β€’ `subscribe` should return an unsubscribe function that removes the listener from the array.