Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redux in a nutshell
function createStore (reducers) {
var state = reducers()
const store = {
dispatch: (action) => {
state = reducers(state, action)
},
getState: () => {
return state
}
}
return store
}
const reducers = (state = { counter: 0 }, action) => {
if (!action) { return state }
switch (action.type) {
case 'INCREMENT':
return { counter: state.counter + 1 }
case 'DECREMENT':
return { counter: state.counter - 1 }
default:
return state
}
}
const store = createStore(reducers)
store.getState() // => { counter: 0 }
store.dispatch({ type: 'INCREMENT' })
store.getState() // => { counter: 1 }
@MariusAlch

This comment has been minimized.

Copy link

MariusAlch commented Nov 11, 2016

Love it, awesome help for beginners or in general if you need to persuade a team to use redux. I encourage you make more of these, for example 'redux-saga' would be a good topic.

@Doko-Demo-Doa

This comment has been minimized.

Copy link

Doko-Demo-Doa commented Mar 19, 2017

This is incredibly simple and easy to understand.

@achshar

This comment has been minimized.

Copy link

achshar commented Apr 22, 2017

IDK, looks overly complicated. Passing functions as arguments never felt "right". Something using the ES16 class model would have felt more natural for this.

@grandadmiralmcb

This comment has been minimized.

Copy link

grandadmiralmcb commented Feb 26, 2019

IDK, looks overly complicated. Passing functions as arguments never felt "right". Something using the ES16 class model would have felt more natural for this.

Honestly, I feel it is more predictable to reason about the behavior of a program using this method. You have a single source of state change and an immutable source of truth. There is some boilerplate but long term it's easier to understand what's going on behavior wise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.