Memoizing intermediary steps
I'm currently using createSelector in the following manner:
import { createSelector } from "reselect"
state = {
fruits: ["Apple", "Banana", "Coconut"],
batter: "Dough"
}
const fruitsSelector = (state, props) => ( state.fruits )
const batterSelector = (state, props) => ( state.batter )
const piesSelector = createSelector(
fruitSelector,
batterSelector,
(fruits, batter) => {
return fruits.map(fruit => {
return pieCreator(fruit, batter)
})
}
)
const fruitInput = (fruit, batter) => (fruit)
const batterInput = (fruit, batter) => (batter)
const pieCreator = createSelector(
fruitInput,
batterInput,
(fruit, batter) => {
return `Baked ${fruit} Pie!`
}
)
console.log( piesSelector(state) )
// ["Baked Apple Pie!", "Baked Banana Pie!", "Baked Coconut Pie!"]
In the above example, pieCreator is an "intermediary" selector. It memoizes the "baking of each pie", so in the future when the list of fruits changes, it doesn't have to "re-bake" all of them:
// Append Pumpkin to the list of fruits
state = {
...state,
fruits: [...state.fruits, "Pumpkin"]
}
console.log( piesSelector(state) )
// ["Baked Apple Pie!", "Baked Banana Pie!", "Baked Coconut Pie!", "Baked Pumpkin Pie!"]
// Apple, Banana, and Coconut did not have to be re-baked!
This works great! However, as you may have noticed, I'm hacking the input selectors in a way they weren't intended to be used. Notice how I'm passing in fruit and batter where state and props are expected.
Is there a better way of doing this?
The reason that parameters have the names state and props is really just to match up with the parameters of mapStateToProps. They could be called anything, you are not doing anything wrong by calling the selectors with whatever value you like.
But I think there is a problem with your example. createSelector only memoizes the last arguments it receives, so mapping it over fruits is going to recompute the function each time. You'll need to switch the memoize function out for something with a larger cache.