Last active
October 14, 2020 10:26
-
-
Save nikparo/d6a9e83faaf1d925faa7ece38287e395 to your computer and use it in GitHub Desktop.
Skip redux subscription updates when state hasn't changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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