Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Beginner

Basic Selectors

Definition

Functions used to extract specific pieces of data from the Redux store state.

Explain Like I'm New

A selector is just a simple arrow function: `(state) => state.auth.user`. You pass this function into the `useSelector` hook so the component knows exactly which slice of the pie it's allowed to eat.

Real World Example

Instead of writing `(state) => state.auth.user` in 10 different components, you define `export const selectUser = (state) => state.auth.user` inside `authSlice.js`, and import that function into your components.

Common Use Cases

  • •Encapsulating state shape
  • •Reusable data extraction

Interactive Example

// userSlice.js
const userSlice = createSlice({ ... });

// Define Selectors alongside the slice
export const selectIsLoggedIn = (state) => state.user.isLoggedIn;
export const selectUsername = (state) => state.user.profile.name;

// Component.js
import { selectUsername } from './userSlice';
import { useSelector } from 'react-redux';

function Header() {
  // Clean, reusable, and resilient to state shape changes!
  const username = useSelector(selectUsername);
}

Interview Questions

basic

  • Where is the best place to define your selector functions?

intermediate

  • If the shape of your state changes (e.g., `state.user` becomes `state.auth.user`), why are selectors helpful?

Flash Cards

Question

Where to define?

Click to reveal answer
Answer

In the same file as the Slice that manages that data (e.g., `userSlice.js`).

Question

Why helpful for shape changes?

Click to reveal answer
Answer

If you hardcoded `state.user` in 50 components, you have to update 50 files. If you used a single `selectUser` selector function, you only have to update the path in ONE file, and all 50 components magically work.