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?