Basic Memoized Selector Creation
Show how to use createSelector for a simple memoized selector that calculates the total price of items in a shopping cart.
import { createSelector } from '@reduxjs/toolkit';
// Selector to get the items array from state
const selectCartItems = state => state.cart.items;
// Memoized selector to calculate the total price of items in the shopping cart
const selectTotalPrice = createSelector(
[selectCartItems],
(items) => items.reduce((total, item) => total + item.price * item.quantity, 0)
);
This code snippet imports createSelector from '@reduxjs/toolkit' and defines a basic selector to get cart items from the state. Then, it defines a memoized selector using createSelector that calculates the total price of items in the shopping cart.