Reputation: 5656
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?
Upvotes: 36
Views: 39492
Reputation: 8774
Use createSelector
only if we want to memoise the function which retrieves store value.
Otherwise it's not required.
Upvotes: 3
Reputation: 67627
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.
Upvotes: 52