Blog>
Snippets

Implementing Redux Selectors with Reselect and ES6 Features

Exhibit how to build efficient selectors for Redux with the Reselect library, leveraging ES6 features like arrow functions for better performance and readability.
import { createSelector } from 'reselect';

// Simple selectors
const getUsers = state => state.users;
const getFilter = state => state.filter;

// Reselect selector which memoizes
// Only recalculates when one of the input selectors return a different value
const getVisibleUsers = createSelector(
  [getUsers, getFilter],
  (users, filter) => users.filter(user => user.name.includes(filter))
);
We are defining simple 'selector functions' that access slices of the Redux store's state. We then compose a 'memoized selector' with Reselect which will only recompute the filtered users list if either the users array or the filter string in state have changed.
// Usage within a React component with the 'useSelector' hook from 'react-redux'
import { useSelector } from 'react-redux';

function UserList() {
  // Uses the memoized selector with useSelector
  // Only rerenders when the output of getVisibleUsers changes
  const visibleUsers = useSelector(getVisibleUsers);

  return (
    // Render only visible users
    <ul>{visibleUsers.map(user => <li key={user.id}>{user.name}</li>)}</ul>
  );
}
This is a practical example of how you use the composed Reselect selector within a React component to select data from the Redux store. The UserList component will only re-render when getVisibleUsers produces a new array of users because of changes to users or filter in the Redux store's state.