React Context can cause unnecessary re-renders. Here's how to optimize it.
The Problem#
Solution 1: Split Contexts#
Solution 2: Separate State and Dispatch#
Solution 3: Memoize Context Value#
Solution 4: Selector Pattern#
Solution 5: Component Composition#
Solution 6: Ref for Non-Reactive State#
Measuring Performance#
Best Practices#
Structure:
✓ Split unrelated state into separate contexts
✓ Separate state from dispatch
✓ Keep contexts small and focused
✓ Memoize context values
Optimization:
✓ Use useMemo for value objects
✓ Use useCallback for functions
✓ Consider selector libraries
✓ Profile before optimizing
Patterns:
✓ Colocate state with usage
✓ Pass children to avoid re-renders
✓ Use refs for non-reactive state
✓ Compose multiple providers
Conclusion#
Context performance issues stem from unnecessary re-renders when any context value changes. Split contexts by domain, separate state from dispatch, memoize values, and consider selector patterns for granular subscriptions. Always profile to identify actual bottlenecks before optimizing.