Reputation: 661
In the useSelector
hook examples of react-redux documentation, there's a code snippet:
const selectNumOfTodosWithIsDoneValue = createSelector(
state => state.todos,
(_, isDone) => isDone,
(todos, isDone) => todos.filter(todo => todo.isDone === isDone).length
)
As we can see, isDone
is a parameter of selectNumOfTodosWithIsDoneValue
. But why is it put in a separate parametric selector, i.e. (_, isDone) => isDone
? Can I write it the following?
const selectNumOfTodosWithIsDoneValue = createSelector(
(state, isDone) => state.todos.filter(todo => todo.isDone === isDone),
filteredTodos => filteredTodos.length
)
What's the difference between the 2 approaches?
Upvotes: 1
Views: 189
Reputation: 67627
The second example will always cause a complete recalculation, because filter()
always returns a new array reference.
While I'm not particularly happy with the current (first) example, it does memoize in that it will only recalculate the length if either state.todos
or isDone
have changed.
Upvotes: 2