Skip to content

Instantly share code, notes, and snippets.

@jhamberg
Last active July 9, 2018 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhamberg/075be0b31d626a6aa13e20394f975a35 to your computer and use it in GitHub Desktop.
Save jhamberg/075be0b31d626a6aa13e20394f975a35 to your computer and use it in GitHub Desktop.
Redux (flux) in 12 lines of code with an example.
const createStore = reducer => {
const subscribers = [];
let state = reducer(undefined, {type: "__init"});
return {
dispatch: action => {
state = reducer(state, action);
subscribers.forEach(fun => fun());
},
subscribe: fun => subscribers.push(fun),
getState: () => state
}
}
// Create a simple counter reducer
const counterReducer = (state = 0, action) => {
switch (action.type) {
case "INCREMENT": return state + 1;
case "DECREMENT": return state - 1;
}
return state; // This is important so __init works
};
// Initialize store and dispatch
const store = createStore(counterReducer);
store.dispatch({type: "INCREMENT"});
store.dispatch({type: "INCREMENT"});
console.log(store.getState()); // Prints "2"
// Subscriber example
const render = () => console.log(`counter: ${store.getState()}`);
store.subscribe(render);
store.dispatch({type: "INCREMENT"}); // Prints "counter: 3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment