Blog>
Snippets

Integrating createSelector with React's useSelector

Explain how to use useSelector in conjunction with createSelector in a functional React component, demonstrating effective state query and minimizing re-renders.
import { createSelector } from 'reselect';
import { useSelector } from 'react-redux';
Import createSelector from reselect and useSelector from react-redux.
const selectTodos = state => state.todos;
const selectFilter = state => state.visibilityFilter;
Define input selector functions. These functions select parts of the state needed by the output selector.
const selectVisibleTodos = createSelector(
  [selectTodos, selectFilter],
  (todos, filter) => {
    switch (filter) {
      case 'SHOW_COMPLETED':
        return todos.filter(t => t.completed);
      case 'SHOW_ACTIVE':
        return todos.filter(t => !t.completed);
      default:
        return todos;
    }
  }
);
Use createSelector to create a memoized selector that computes derived data. It takes an array of input selectors and an output selector that calculates the filtered todos based on the current visibility filter.
function TodoList() {
  // Use the useSelector hook with the memoized selector function.
  const visibleTodos = useSelector(selectVisibleTodos);
  return (
    // Render your component with the derived state
    <ul>
      {visibleTodos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}
Create the TodoList functional component which uses useSelector to get the visible todos from the Redux store. The useMemo hook is used to ensure the component only re-renders when visibleTodos have actually changed.