Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about `useSelector` and `createSelector` with Redux toolkit

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?

like image 348
Joji Avatar asked Aug 19 '20 19:08

Joji


1 Answers

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.

like image 175
markerikson Avatar answered Sep 18 '22 10:09

markerikson