Blog>
Snippets

Optimizing React Component Renders with useSelector

Showcase how to use the useSelector hook with memoization to only re-render components when specific parts of the form state change.
import { useSelector, shallowEqual } from 'react-redux';

const selectUserDetails = state => state.user.details;
const selectUserLoadingStatus = state => state.user.isLoading;

const UserDetails = () => {
  // Use shallowEqual for comparing the returned object
  const userDetails = useSelector(selectUserDetails, shallowEqual);

  return (
    // Your JSX component that uses userDetails
  );
};

const UserLoadingStatus = () => {
  // Only the loading status part of the state will trigger a re-render
  const isLoading = useSelector(selectUserLoadingStatus);

  return (
    // Your JSX component that indicates loading status
  );
};
This example defines two components, UserDetails and UserLoadingStatus. Each uses the useSelector hook to access only the specific parts of the state it needs (details and loading status, respectively). The shallowEqual function ensures that UserDetails only re-renders when the details object has actually changed, rather than on every state update.