Search code examples
reactjsreduxredux-toolkit

Why put input selector that is not used in the prompters of the external prompter of createSelector?


When creating a new selector with createSelector that can receive an extra parameter, it is necessary to add the corresponding state part (items) next to the external selector input which, in the case shown, would be categoryName. Why is this necessary?

Furthermore, when putting (_, categoryName) => categoryName, it worked the same way, what is the use of this first parameter?

print of items slice

print of main component

[items, (categoryName) => categoryName],

and it just not work


Solution

  • ...it is necessary to add the corresponding state part (items) next to the external selector input... Why is this necessary?

    This is necessary because all selector functions are passed the current Redux store, e.g. state, as the first, and usually only, argument.

    Furthermore, when putting (_, categoryName) => categoryName, it worked the same way, what is the use of this first parameter?

    It worked the same way because "_" is just a valid Javascript identifier, same as "items" had you used (items, categoryName) => categoryName. Typically we name that first argument state, e.g. (state, categoryName) => categoryName since that is what it actually is. In this scenario you still need to name the first argument something so you can really access the second argument, the "extra" parameter that you want to use in the computed selector function.

    [items, (categoryName) => categoryName],

    and it just not work

    This doesn't work because you have named the passed Redux state categoryName and are not consuming the passed extra parameter. In the selector function categoryName will just be the entire state value.

    Since the state argument is effectively a "throw-away" variable that isn't referenced, there is a naming convention to use "_" to indicate that a named variable is intentionally "unused" or is an "internal implementation detail" and isn't meant to be used or referenced.

    const items = state => state.items;
    
    createSelector(
      [
        items,                            // <-- selects items state
        (_, categoryName) => categoryName // <-- "selects" categoryName
      ],
      (items, categoryName) => {
        // logic to compute a value using the items state
        // and passed category name value
      },
    );