Skip to content

Instantly share code, notes, and snippets.

@nikparo
Last active October 14, 2020 10:26
Show Gist options
  • Save nikparo/d6a9e83faaf1d925faa7ece38287e395 to your computer and use it in GitHub Desktop.
Save nikparo/d6a9e83faaf1d925faa7ece38287e395 to your computer and use it in GitHub Desktop.
Skip redux subscription updates when state hasn't changed
import { createStore as basicCreateStore } from 'redux';
export const skipSameStateEnhancer = createStore => (
reducer,
initialState,
enhancer,
) => {
const store = createStore(reducer, initialState, enhancer);
// Create an in-between store so that we can skip subscription updates where nothing changed.
// Using basicCreateStore to not mess with e.g. redux-dev-tools. Not sure if it matters.
const subStore = basicCreateStore(() => {});
let cachedState = store.getState();
store.subscribe(() => {
const state = store.getState();
if (state !== cachedState) {
cachedState = state;
subStore.dispatch({ type: 'trigger' });
}
});
return {
...store,
subscribe: subStore.subscribe,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment