Redux & Redux Toolkit
/Advanced
Memoization
Definition
An optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
Explain Like I'm New
If you ask me 'What is 1,234 x 5,678?', it takes me 10 minutes to calculate the answer. If you ask me the exact same question 5 seconds later, I don't recalculate it. I just remember the answer. That is memoization.
Real World Example
Using `useMemo()` in React components to prevent an expensive sorting algorithm from running on an array of Redux data every time a totally unrelated piece of state updates.
Common Use Cases
- •Preventing UI lag
- •Optimizing derived state calculations
Interactive Example
import { useMemo } from 'react'; import { useSelector } from 'react-redux'; function ExpensiveComponent() { const users = useSelector(state => state.users); // ✅ GOOD: This heavy calculation ONLY runs when 'users' actually changes! // If this component re-renders because 'theme' changed, this math is skipped. const sortedUsers = useMemo(() => { console.log('Running heavy sort algorithm...'); return [...users].sort((a, b) => a.name.localeCompare(b.name)); }, [users]); return <div>{sortedUsers.length} Users</div>; }
Interview Questions
basic
- What library does Redux use to implement memoized selectors?
intermediate
- If a memoized selector receives the exact same arguments as last time, does the internal function execute?