0
0
Reactframework~8 mins

Consuming context in React - Performance & Optimization

Choose your learning style9 modes available
Performance: Consuming context
MEDIUM IMPACT
This affects interaction responsiveness and rendering speed when components read shared data.
Accessing shared data in multiple components
React
Split context into smaller contexts or use memoized selectors to consume only needed parts.
const value = useContext(MyContext);
const selected = useMemo(() => value.part, [value.part]);
Reduces unnecessary re-renders by limiting updates to components that need specific data.
📈 Performance GainFewer re-renders, smoother interaction, and lower CPU usage.
Accessing shared data in multiple components
React
const value = useContext(MyContext);
// used in many components deeply nested
// context value changes frequently
All components consuming the context re-render on every context change, even if they don't use all data.
📉 Performance CostTriggers many re-renders and layout recalculations, increasing INP and CPU usage.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Single large context with frequent changesMany components re-renderMultiple reflows per updateHigh paint cost[X] Bad
Split context or memoized selectorsOnly necessary components re-renderSingle or few reflowsLower paint cost[OK] Good
Rendering Pipeline
When context changes, React schedules re-renders for all consuming components. This triggers Style Calculation, Layout, Paint, and Composite stages for updated components.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint stages are most expensive due to re-rendering many components.
Core Web Vital Affected
INP
This affects interaction responsiveness and rendering speed when components read shared data.
Optimization Tips
1Avoid putting frequently changing data in a single large context.
2Split context into smaller pieces to limit re-render scope.
3Memoize context values and selectors to prevent unnecessary updates.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens when a React context value changes?
ANo components re-render automatically
BOnly components that explicitly call setState re-render
CAll components consuming that context re-render
DOnly the top-level component re-renders
DevTools: React DevTools Profiler
How to check: Record interactions and look for components re-rendering on context changes. Check if unnecessary components update.
What to look for: High number of re-renders and long commit times indicate poor context consumption performance.