0
0
Reactframework~8 mins

Updating state in React - Performance & Optimization

Choose your learning style9 modes available
Performance: Updating state
HIGH IMPACT
This affects how quickly the UI updates after user interaction and how smoothly the app responds to input.
Updating multiple related state values in a React component
React
const [state, setState] = useState({ count: 0, text: '' });

function updateBoth() {
  setState(prev => ({ ...prev, count: prev.count + 1, text: 'Updated' }));
}
Single state update batches changes, causing only one re-render and layout recalculation.
📈 Performance GainTriggers 1 re-render and 1 layout recalculation, improving responsiveness
Updating multiple related state values in a React component
React
const [count, setCount] = useState(0);
const [text, setText] = useState('');

function updateBoth() {
  setCount(count + 1);
  setText('Updated');
}
Multiple separate state updates cause multiple re-renders, slowing UI responsiveness.
📉 Performance CostTriggers 2 re-renders and 2 layout recalculations per update
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Multiple separate state updatesMultiple updates to virtual DOMMultiple reflows triggeredHigher paint cost due to repeated updates[X] Bad
Single batched state updateOne update to virtual DOMSingle reflow triggeredLower paint cost with one update[OK] Good
Rendering Pipeline
When state updates, React schedules a re-render of the component. This triggers the browser's style calculation, layout, paint, and composite steps to update the UI.
JavaScript execution
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckMultiple state updates cause repeated JavaScript execution and layout recalculations, increasing input delay.
Core Web Vital Affected
INP
This affects how quickly the UI updates after user interaction and how smoothly the app responds to input.
Optimization Tips
1Batch multiple related state updates into one to reduce re-renders.
2Use functional updates to avoid stale state and unnecessary renders.
3Avoid updating state in ways that cause layout thrashing or repeated DOM changes.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with calling multiple setState functions separately in React?
AIt increases the bundle size significantly.
BIt causes multiple re-renders and layout recalculations.
CIt blocks the main thread for several seconds.
DIt causes the browser to reload the page.
DevTools: React DevTools and Performance panel
How to check: Open React DevTools Profiler, record while triggering state updates, then check number of renders. Use Performance panel to see layout and paint events.
What to look for: Look for fewer component renders and shorter layout/paint durations indicating efficient state updates.