Context can cause unnecessary re-renders if not used carefully. Here's how to optimize it.
The Problem#
Split Contexts#
Separate State and Dispatch#
Memoize Provider Value#
Selector Pattern#
Compound Components#
Preventing Child Re-renders#
Context with Immer#
Testing Context#
Best Practices#
Structure:
✓ Split contexts by update frequency
✓ Separate state and dispatch
✓ Keep contexts focused
✓ Use custom hooks for access
Performance:
✓ Memoize provider values
✓ Use selectors for granular access
✓ Prevent unnecessary re-renders
✓ Profile with React DevTools
Patterns:
✓ Create context factories
✓ Use compound components
✓ Provide meaningful defaults
✓ Handle missing providers
Organization:
✓ Co-locate context with components
✓ Export hooks, not contexts
✓ Document context shape
✓ Test providers separately
Conclusion#
Context optimization prevents unnecessary re-renders. Split contexts by concern, separate state from dispatch, memoize values, and use selectors for granular access. Profile with React DevTools to identify performance issues and apply these patterns strategically.