Redux & Redux Toolkit
/Advanced
Memoized Selectors
Definition
Selectors that cache their previous inputs and outputs. If the state hasn't changed, they return the cached result instantly instead of recalculating the derived state.
Explain Like I'm New
If your selector sorts an array of 10,000 users alphabetically, that takes processing power. If the user clicks a button that changes the 'Dark Mode' theme, the component re-renders and the selector runs again, sorting the 10,000 users again for no reason. A memoized selector remembers the sorted list, and says 'The users didn't change, here is the cached list instantly.'
Real World Example
Using the `createSelector` utility from the `Reselect` library (which is built into RTK) to prevent expensive map/filter/reduce operations from freezing the UI.
Common Use Cases
- •Performance optimization
- •Expensive derived state calculations
Interactive Example
import { createSelector } from '@reduxjs/toolkit'; // 1. Basic input selectors (Not memoized, just grabs the raw data) const selectUsers = state => state.users.data; const selectSearchTerm = state => state.users.searchTerm; // 2. Memoized Selector (Heavy lifting!) // It only recalculates IF 'selectUsers' or 'selectSearchTerm' change! export const selectFilteredUsers = createSelector( [selectUsers, selectSearchTerm], // Input selectors (users, searchTerm) => { // Output function (Does the math) console.log('Calculating filtered users! (This is skipped if cached)'); return users.filter(user => user.name.includes(searchTerm)); } );
Interview Questions
basic
- What RTK function is used to create a memoized selector?
intermediate
- If a memoized selector returns a new array using `.map()`, will it cause unnecessary re-renders?