reselect icon indicating copy to clipboard operation
reselect copied to clipboard

How to combine with a non dependent state in Redux?

Open terencechow opened this issue 10 years ago • 5 comments

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
         }
    }

terencechow avatar Jan 14 '16 22:01 terencechow

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 avatar Jan 15 '16 14:01 ellbee

@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?

terencechow avatar Jan 15 '16 15:01 terencechow

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 avatar Jan 15 '16 15:01 ellbee

@ellbee I was looking for the answer of the same problem too. Thanks :+1:

southerncross avatar Jan 30 '16 02:01 southerncross

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.

deelan avatar Feb 07 '16 00:02 deelan