Parameterized Selectors
Illustrate the creation of a parameterized selector to filter or query the state based on passed arguments.
import { createSelector } from 'reselect';
// This is the base selector which gets the whole todos list from the state
const selectTodos = state => state.todos;
// This factory function returns a memoized selector that filters todos by a specific category
function makeSelectTodosByCategory(category) {
return createSelector(
[selectTodos],
(todos) => todos.filter(todo => todo.category === category)
);
}
A factory function that returns a parameterized selector for filtering todos by category. It uses reselect to create a memoized selector that won't recompute unless the input todos list changes.
// Usage within a React component
import React from 'react';
import { useSelector } from 'react-redux';
function FilteredTodoList({ category }) {
// Call the factory function to get a selector for the specific category
const selectTodosByCategory = makeSelectTodosByCategory(category);
// Use the selector with useSelector in the component
const todos = useSelector(selectTodosByCategory);
return (
// ... render the list of todos ...
);
}
Demonstrates how to use the parameterized selector within a React component. A specific memoized selector is created for the given category and provided to useSelector to get the filtered list of todos.