Skip to content

Instantly share code, notes, and snippets.

@valmassoi
Created January 7, 2020 15:34
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 valmassoi/72dbd47d18c335dcab440e444bc58a9a to your computer and use it in GitHub Desktop.
Save valmassoi/72dbd47d18c335dcab440e444bc58a9a to your computer and use it in GitHub Desktop.
redux createStore from scratch
// https://egghead.io/lessons/react-redux-implementing-store-from-scratch
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
// calculate new state
state = reducer(state, action)
// notify subscribers know of state change
listeners.forEach(listener => listener());
}
const subscribe = (listener) => {
// keep list of subscribers
listeners.push(listener);
// unsubscribe by calling again
return () => {
listeners = listeners.filter(l => l !== listener);
}
}
// init state
dispatch({});
return { getState, dispatch, subscribe };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment