Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Beginner

useSelector()

Definition

A React hook that allows you to extract data from the Redux store state. The hook takes a selector function as an argument, which receives the entire Redux state and returns the specific piece of data you need.

Explain Like I'm New

The 'Reader'. If your component needs to know the user's name from the Redux store, you use `useSelector`. The magical part is that if the user's name changes in the store, `useSelector` forces your component to instantly re-render with the new name.

Real World Example

A Navbar component using `useSelector((state) => state.cart.totalItems)` to display a little red badge showing how many items are in the shopping cart.

Common Use Cases

  • •Reading data from Redux
  • •Subscribing to state changes

Interactive Example

import { useSelector } from 'react-redux';

function UserProfile() {
  // Pass a function that takes the whole state, and returns just what you need
  const username = useSelector((state) => state.auth.username);
  const theme = useSelector((state) => state.ui.theme);

  return (
    <div className={`theme-${theme}`}>
      <h1>Welcome back, {username}!</h1>
    </div>
  );
}

Interview Questions

basic

  • If `state.user` changes, will a component using `useSelector(state => state.cart)` re-render?

intermediate

  • Why should you select the smallest possible piece of state?

Flash Cards

Question

Will it re-render?

Click to reveal answer
Answer

No! `useSelector` is highly optimized. It only triggers a re-render if the EXACT piece of data you selected (`state.cart`) changes. Since only `user` changed, the cart component stays perfectly still.

Question

Why select smallest?

Click to reveal answer
Answer

If you do `const state = useSelector(state => state)`, your component will re-render every single time ANY data in the entire app changes, causing massive performance issues.