john otor
john otor

Reputation: 59

How to make a selector not re-render when not called

i want to memorize the selectors so that if one of the selector is being called the others doesn't re-render, for instance if i click on the cart icon to show the dropdown to show the cart, the itemCount selector should not re-render and log "i am being called" but it still re-render with the way i wrote my code. please does anyone know a solution for this? i am using reselect

// cartSelector.js
const selectCart = (state) => state.cart;

export const selectCartItems = createSelector(
  [selectCart],
  (cart) => cart.cartItems
);

export const hideCart = createSelector([selectCart], (cart) => cart.hidden);

export const selectCartItemsCount = createSelector(
  [selectCartItems],
  (cartItems) => cartItems.reduce((acc, cartitem) => acc + cartitem.quantity, 0)
);

// App.js
const hidden = useSelector((state) => hideCart(state));

  const cartItems = useSelector((state) => selectCartItems(state));

  const itemCount = useSelector((state) => {
    console.log("i am being called");
    return selectCartItemsCount(state);
  });

Upvotes: 0

Views: 457

Answers (1)

phry
phry

Reputation: 44078

You have a misconception here. Every selector is always called after every dispatch. That has nothing to do with a render. A render only occurs for a component if one of those selectors returned a different reference/plain value than on the last call.

=> it is normal that that selector is always called and there is no way of preventing the selector to be called.

Upvotes: 1

Related Questions