useMemo and useCallback for Performance
Memoize expensive calculations with useMemo and stable function references with useCallback to prevent unnecessary child re-renders.
React's Default Behaviour
By default, React re-renders a component whenever its state or parent re-renders. Child components also re-render even if their props haven't changed. For most components this is fine — React is fast.
useMemo — Memoize Expensive Values
useMemo(fn, deps) caches the result of a computation. The function only runs when the dependencies change. Use it for expensive calculations that would be wasteful to repeat every render.
const expensiveResult = useMemo(() => {
return items.filter(item => item.category === category).sort((a, b) => a.price - b.price);
}, [items, category]);
// Only recalculates when items or category changesAll lessons in this course
- useContext for Global State
- useReducer for Complex State
- useMemo and useCallback for Performance
- Custom Hooks: Extracting Reusable Logic