Redux reimplemented in 12 lines of code

Dale L. Jefferson
Frontend Weekly
1 min readDec 29, 2016

--

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

I like to reimplement libraries I use, this allows me to better understand how they work, above is my minimal implementation of Redux. 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.

--

--