Blog>
Snippets

Using Memoized Selectors with Paginated Data

Present an example of creating a memoized selector using createSelector from Reselect to compute and retrieve paginated data for a component without unnecessary re-renders.
import { createSelector } from 'reselect';

// Selector to extract paginated data from state
const selectPaginatedItems = state => state.items.paginatedData;

// Selector to extract current page from state
const selectCurrentPage = state => state.items.currentPage;

// Selector to extract page size from state
const selectPageSize = state => state.items.pageSize;

// Memoized selector to compute paginated items for the current page
export const selectCurrentPageItems = createSelector(
  [selectPaginatedItems, selectCurrentPage, selectPageSize],
  (paginatedItems, currentPage, pageSize) => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = currentPage * pageSize;
    return paginatedItems.slice(startIndex, endIndex);
  }
);
This code defines a memoized selector `selectCurrentPageItems` using `createSelector` from Reselect. It uses three selectors to retrieve the paginated data, the current page, and the page size from the Redux state. It then computes and returns the items for the current page by slicing the paginated items array based on the calculated start and end indices.