Blog>
Snippets

Using Selectors for Efficient State Querying

Provide code snippets demonstrating the use of selectors to retrieve and memoize slices of the state, optimizing the data flow and reducing unnecessary renders.
import { createSelector } from 'reselect';

// Assume we have a state shape like this:
// { user: { name: 'Alice', age: 30 }, posts: { byId: {} } }

// Selector to get the user object
const selectUser = state => state.user;

// Selector to get the user's name
const selectUserName = createSelector(
  [selectUser],
  (user) => user.name
);

// In a React component, we would use the selector like this:
import { useSelector } from 'react-redux';

const UserName = () => {
  const userName = useSelector(selectUserName);
  return <div>User name: {userName}</div>;
};
This example defines two selectors using the 'reselect' library. The first is a simple selector that retrieves the 'user' state. The second is a memoized selector created with 'createSelector' that derives the 'name' from the 'user' state. Using these selectors in conjunction with 'useSelector' hook allows a React component to subscribe only to the relevant pieces of state, avoiding unnecessary re-renders when other parts of the state change.