Dale Jefferson

Dale Jefferson

Father, Husband, Classical Liberal, Software Developer

Redux reimplemented in 12 lines of code

By Dale Jefferson. Published
JavaScript, Redux

I like to reimplement libraries I use, this allows me to better understand how they work, below is my minimal implementation of Redux.

const createStore = reducer => {
  let onChange;
  let state = reducer(undefined, {});
  return {
    getState: () => state,
    subscribe: fn => (onChange = fn),
    dispatch: action => {
      state = reducer(state, action);
      onChange();
    }
  };
};

This works with the example on the Redux homepage below.

const counter = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
};

const store = createStore(counter);

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

store.dispatch({type: "INCREMENT"}); // 1
store.dispatch({type: "INCREMENT"}); // 2
store.dispatch({type: "DECREMENT"}); // 1

Obviously this only has a fraction of the real Redux API.