Skip to content

Instantly share code, notes, and snippets.

@MarcoWorms
Last active June 3, 2024 04:42
Show Gist options
  • Save MarcoWorms/30758235f05faec844b8c06ce2e5bac9 to your computer and use it in GitHub Desktop.
Save MarcoWorms/30758235f05faec844b8c06ce2e5bac9 to your computer and use it in GitHub Desktop.
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 }
@Doko-Demo-Doa
Copy link

This is incredibly simple and easy to understand.

@achshar
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
Copy link

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.

@MarcoWorms
Copy link
Author

MarcoWorms commented Nov 13, 2020

Just saw this got some traction, thanks for the nice comments!

@achshar hey there, in my opinion there are different ways to achieve the same goals when dealing tools like JS, you could totally achieve the same behavior by using classes. Using the redux-style solution means that the developer is prioritizing predictability in state management, I wouldn't say that this example is "how state should be done for any application", it's more like "here's the barebones of redux philosophy without having to care about importing libs"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment