Selector with Multiple Input Selectors
Demonstrate how createSelector takes multiple input selectors and re-computes only when one of the inputs changes.
const { createSelector } = require('reselect');
// Input selectors
const selectNumOfApples = state => state.apples;
const selectNumOfOranges = state => state.oranges;
// A memoized selector that adds the number of apples and oranges
const selectTotalFruits = createSelector(
[selectNumOfApples, selectNumOfOranges],
(numApples, numOranges) => numApples + numOranges
);
// Example state
const state = { apples: 3, oranges: 5 };
// Here we use the selector
console.log(selectTotalFruits(state)); // Outputs: 8 - the function computes the total
console.log(selectTotalFruits(state)); // Outputs: 8 - the function returns the memoized result
This example defines two input selectors for the number of apples and oranges in the state. It creates a memoized selector to calculate the total fruits. On the second call with the same state, it returns the memoized result without re-computing.