Blog>
Snippets

Handling Nested or Derived Data with createSelector

Use createSelector to efficiently handle derived data from a nested state structure, like finding the number of unread notifications.
import { createSelector } from '@reduxjs/toolkit';

// Selector to get notifications state slice
const selectNotifications = state => state.notifications;

// Selector to get only the unread notifications from the notifications state slice
const selectUnreadNotifications = createSelector(
  [selectNotifications],
  notifications => notifications.filter(notification => !notification.read)
);

// Selector to get the count of unread notifications
const selectUnreadNotificationCount = createSelector(
  [selectUnreadNotifications],
  unreadNotifications => unreadNotifications.length
);
This code snippet creates three selectors using Redux Toolkit's createSelector. The first one, selectNotifications, retrieves the notifications slice of the state. The second, selectUnreadNotifications, uses the first selector as an input selector to derive only those notifications that are unread. Lastly, selectUnreadNotificationCount computes the count of unread notifications by using the output of selectUnreadNotifications.