DEV Community

Cover image for Redux reimplemented in 12 lines of code
Dale L. Jefferson
Dale L. Jefferson

Posted on • Edited on • Originally published at dalejefferson.com

Redux reimplemented in 12 lines of code

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.

Top comments (1)

Collapse
 
vonheikemen profile image
Heiker

And with a few more you can have redux-thunk.

const createStore = reducer => {
  let onChange;
  let state = reducer(undefined, {});
+ let store = {
- return {
    getState: () => state,
    subscribe: fn => (onChange = fn),
    dispatch: action => {
+     if(typeof action === 'function') {
+       return action(store.dispatch, store.getState);
+     }
+
      state = reducer(state, action);
      onChange();
    }
  };

+ return store;
};

A bit intrusive but it does the job.