32

I am new to Redux and Redux toolkit. I learned that createSelector can accept multiple input selectors, which can be provided as separate arguments or as an array. The results from all the input selectors are provided as separate arguments to the output selector.

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

const selectABC = createSelector(
    [selectA, selectB, selectC],
    (a, b, c) => {
        // do something with a, b, and c, and return a result
        return a + b + c;
    }
);

my question is, if I only care about one simple state, can I just use useSelector like this

const selectA = state => state.a;

const a = useSelector(selectA)

what's the difference between the two usages?

Joji
  • 4,703
  • 7
  • 41
  • 86

2 Answers2

45

A "selector" is any function that accepts the Redux state tree as an argument, and returns some extracted or derived data. That includes plain functions like you showed.

In many cases, you want to memoize the calculation of the results, such as mapping over an array of items, so that it's not re-calculated unless the inputs have changed. Reselect's createSelector creates memoized selector functions that only recalculate the output if the inputs change.

For more details, see my post Using Reselect Selectors for Encapsulation and Performance , as well as the "Performance and Normalizing Data" page in the new "Redux Essentials" core docs tutorial.

markerikson
  • 63,178
  • 10
  • 141
  • 157
  • thanks for the reply! actually I wonder if we are just for getting a piece of state from the state and return it directly, we should just use a plain function as opposed to `createSelector` or we should always use `createSelector` by default? – Joji Aug 19 '20 at 19:53
  • 11
    I would recommend only using `createSelector` if there's actual derived state involved, ie, `state => state.items.map(item => item.id)` – markerikson Aug 19 '20 at 20:02
  • @markerikson Hey Mark, Let's say I have an array of objects and my selector extracts this via useSelector. I'm mapping the array and extract the objects, render JSX etc.. Casual stuff. But Let's also say that all I need to utilize in my component is 3 fields of that object (out of, say 9 fields). Would you (personally) employ memoization in this case ? No sorting, calculation, derivation. Just 'chopping' the object. Would it be plausible to memoize in this specific use case? ( no nested arrays/objects involved). I feel not so comfortable making memoization decisions – emre-ozgun Jan 05 '23 at 06:46
  • 1
    I don't see any real reason to memoize that, _unless_ the other fields in the object are changing much more frequently than the fields you actually need. – markerikson Jan 07 '23 at 06:14
2

Use createSelector only if we want to memoise the function which retrieves store value.

Otherwise it's not required.

Yuvraj Patil
  • 7,944
  • 5
  • 56
  • 56