Blog>
Snippets

useSelector with createSelector in React

Showcase the integration of createSelector with the useSelector hook in a React functional component, explaining how to select state in a performant way.
import { createSelector } from 'reselect';
import { useSelector } from 'react-redux';
Import createSelector from reselect and useSelector from react-redux.
const selectProducts = state => state.products;
const selectFilter = state => state.filter;
const selectFilteredProducts = createSelector(
  [selectProducts, selectFilter],
  (products, filter) => products.filter(product => product.category === filter)
);
Define selectors to select parts of the state. Create a memoized selector using createSelector, which computes filtered products based on the current filter category.
function ProductList() {
  const filteredProducts = useSelector(selectFilteredProducts);
  // Now we can use `filteredProducts` in our component.
  return (
    <ul>
      {filteredProducts.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}
Create a functional component ProductList which uses the useSelector hook to get the filtered products from state using the selectFilteredProducts selector.