reduxjs / reselect

Selector library for Redux
MIT License
19.03k stars 671 forks source link

Question: should OutputSelector be used as an InputSelector? #702

Closed cchaonie closed 6 months ago

cchaonie commented 6 months ago

Hi, thanks for the amazing work. After upgrading to v5, I encountered an issue with the development check.

An OutputSelector will contain a ResultFunction which will do a transformation of the data.

const state = { a : 1, b : 2, c : 3 };

const selectA = state => state.a;
const selectB = state => state.b;
const selectC = state => state.c;

const selectAB = createSelector(selectA, selectB, (a, b) => ({a, b})); // transformation, always returns a different reference.

const selectABC1 = createSelector(selectA, selectB, selectAB, (a, b, c) => ({a, b, c}));
const selectABC2 = createSelector(selectA, selectB, (a, b) => ({a, b, c: { a, b }}));

Which one is the correct usage, selectABC1 or selectABC2?

markerikson commented 6 months ago

I'm not sure I understand the question. Both of those appear to be valid selector definitions. Can you clarify the question?

aryaemami59 commented 6 months ago

Correct me if I'm wrong but I believe you're asking "Can we use a memoized selector created using createSelector and pass it as an input selector to another selector that is being created with createSelector?" If that's the question, the answer is yes, it's part of what makes Reselect awesome. Composable memoized selectors!

const selectAdultUsers = createSelector([state => state.users], users =>
  users.filter(user => user.age > 18),
)

const selectAdultUsersIds = createSelector([selectAdultUsers], adultUsers =>
  adultUsers.map(adultUser => adultUser.id),
)

I believe what you're concerned about with regards to the specific scenario you've mentioned above, is that you're using an output selector like selectAB as in input selector for selectABC1 but since selectAB returns a new reference in its result function, you're worried that it might break memoization, well you can rest easy because it will not. In fact that is pretty much what composable selectors are supposed to look like. We put some dev mode checks in place to catch potential errors like the one you're concerned about, check your console output if you see there is nothing there after calling the output selector, then that should provide some reassurance that you're not going down the wrong path. And to get some even more reassurance you can always look at the docs as well.

cchaonie commented 6 months ago

@markerikson @aryaemami59 Really appreciate your answers. @aryaemami59 's answer is the one I needed exactly.