Blog>
Snippets

Using useSelector with Memoized Selectors

Illustrate the use of useSelector with a memoized selector in a functional React component, ensuring minimal renders.
import { createSelector } from 'reselect';
import { useSelector } from 'react-redux';

// Define a memoized selector using createSelector
const selectCartItems = state => state.cart.items;
const selectCartItemsCount = createSelector(
  [selectCartItems],
  (items) => items.reduce((total, item) => total + item.quantity, 0)
);

// Functional React component using the memoized selector with useSelector
const CartItemsCountComponent = () => {
  // Use useSelector with the memoized selector to get the derived state
  const itemCount = useSelector(selectCartItemsCount);

  return (
    <div>
      {`Number of items in the cart: ${itemCount}`}
    </div>
  );
};

export default CartItemsCountComponent;
A memoized selector 'selectCartItemsCount' is created using 'createSelector' from Reselect library. It calculates the total count of items in a cart. Then, useSelector is used within a functional React component 'CartItemsCountComponent' to access this derived state with minimal re-renders, as it only recalculates when the cart items change.