This repository was archived by the owner on Nov 10, 2021. It is now read-only.
This repository was archived by the owner on Nov 10, 2021. It is now read-only.
[Question] Why multi store subscriptions? #33
Closed
Description
Just for curiosity, why you've opted for a multi-store subscription model instead of subscribing to the store in a top-level Provider?
Something like:
const ReduxStateContext = React.createContext()
function ReduxStateProvider({ store, children }) {
const [state, setState] = React.useState(() => store.getState())
useEffect(() => {
let willUnsubscribe = false
const checkForUpdates = () => {
if (willUnsubscribe) return
setState(prevState => {
const nextState = store.getState()
return shallowEqual(prevState, nextState) ? prevState : nextState
})
}
checkForUpdates()
const unsubscribe = store.subscribe(checkForUpdates)
return () => {
willUnsubscribe = true
unsubscribe()
}
}, [store])
return (
<ReduxStateContext.Provider value={state}>
{children}
</ReduxStateContext.Provider>
)
}
export function useMappedState(mapState) {
const state = useContext(ReduxStateContext)
const [derivedState, setDerivedState] = useState(() => mapState(state))
useEffect(() => {
setDerivedState(prevDerivedState => {
const nextDerivedState = mapState(state)
return shallowEqual(prevDerivedState, nextDerivedState)
? prevDerivedState
: nextDerivedState
})
}, [state])
// It might not even need useEffect() 🤔 (getDerivedStateFromProps)
setDerivedState(prevDerivedState => {
const nextDerivedState = mapState(state)
return shallowEqual(prevDerivedState, nextDerivedState)
? prevDerivedState
: nextDerivedState
})
return derivedState
}
Only the ReduxStateProvider
subscribes to store updates, then it passes the update down to all consumers. Consumers have a chance to bail out by comparing prevDerivedState
with nextDerivedState
.
Metadata
Metadata
Assignees
Labels
No labels