How to combine with a non dependent state in Redux?
I have the following selector:
export const selector = createSelector(
(state) => state,
(state) => {
return {
computedState: state.A + state.B
}
}
When I connect with connect(selector) I get computedState in my props.
However I have another state that I would like to use in my props, let's call it state.C
How do I access state.C in my props? If I change my selector to the below, does that mean changes in state.C will recompute my computedState props? If so, then I shouldn't put state.C in my selector. If that is the case, how do I connect state.C into my connect function for redux? If the below is the correct way of including stateC please confirm that it won't recompute when stateC changes. Thanks!
export const selector = createSelector(
(state) => state,
(state) => {
return {
computedState: state.A + state.B,
state.C
}
}
You can combine selectors as follows:
export const computedStateSelector = createSelector(
state => state.A,
state => state.B,
(A, B) => {
return state.A + state.B
})
export const selector = createSelector(
computedStateSelector,
state => state.C,
(computedState, C) => {
return {
computedState,
C
}
})
@ellbee Doesn't this mean, computedState will update whenever C updates? Isn't that contrary to what we want with a reselector? Since computedState doesn't depend on C why would I want it to recalculate?
computedStateSelector will recalculate when its arguments change which are state.A and state.B. When C changes but not A or B, computedStateSelector will return the cached value of A + B and not recalculate.
@ellbee I was looking for the answer of the same problem too. Thanks :+1:
Thanks for this solution, @ellbee . Might be worth putting in the docs since I expect it's a pretty common question when working with Redux apps and it was... difficult... to find this thread.