Blog>
Snippets

Creating Unique Selector Instances

Provide an example of creating unique selector instances within React components to avoid unnecessary re-renders when the global state changes.
import { createSelector } from 'reselect';

// Selector factory that returns a memoized selector based on the category
function makeSelectItemsByCategory() {
  return createSelector(
    [state => state.items, (_, category) => category],
    (items, category) => items.filter(item => item.category === category)
  );
}

export default makeSelectItemsByCategory;
Defines a selector factory function that creates a memoized selector for filtering items by category.
import React from 'react';
import { useSelector } from 'react-redux';
import makeSelectItemsByCategory from './selectors';

function CategoryComponent({ category }) {
  // Create a unique memoized selector instance for this component
  const selectItemsByCategory = React.useMemo(
    makeSelectItemsByCategory,
    [category] // Dependency array
  );

  // Use the selector with the current category prop
  const items = useSelector(state => selectItemsByCategory(state, category));

  return (
    <div>
      {/* Render items here */}
    </div>
  );
}

export default CategoryComponent;
Uses the selector factory in a React component to create a memoized selector instance that depends on the component's props.