Understanding the Render Cycle
React is fast, but unnecessary re-renders can slow down your application. A re-render happens when a component's state or props change. Performance optimization in React is primarily about ensuring that components only re-render when absolutely necessary.
- Memoization with React.memo
By default, when a parent component re-renders, all its children re-render too. Wrapping a child component in React.memo tells React to skip rendering the component if its props haven't changed (using shallow comparison).
- Stabilizing References: useCallback & useMemo
If you pass a function or an object as a prop to a memoized component, React.memo will fail because functions and objects are recreated on every render (new memory reference). Use useCallback for functions and useMemo for objects/arrays to keep references stable.
- Windowing & Virtualization
Rendering 10,000 DOM nodes at once will crash most browsers. 'Windowing' (or Virtualization) is a technique where you only render the items currently visible in the viewport. As the user scrolls, nodes are recycled.
- React-window: A lightweight library for rendering large lists and tabular data.
- React-virtualized: A more feature-heavy alternative for complex grid layouts.
- Performance Gain: Reduces initial load time and memory usage by 90% in large lists.
- Transition API (useTransition)
Introduced in React 18, the useTransition hook allows you to mark state updates as 'non-urgent'. This keeps the UI responsive (e.g., typing in an input) while a heavy update (e.g., filtering a list) happens in the background.
Optimization Comparison
| Technique | Problem Solved | When to use |
|---|---|---|
| React.memo | Unnecessary child re-renders | Pure components with stable props |
| useCallback | Changing function references | Passing functions to memoized children |
| Lazy Loading | Large bundle size / slow initial load | Routes or heavy components |
| Virtualization | DOM bloat from large lists | Lists/Grids with >100 items |
| useDeferredValue | UI lag during state updates | Filtering or heavy visual computations |