Back to Blog
ReactContextPerformanceSelectors

React Context Selectors Pattern

Optimize React Context with selectors. Prevent unnecessary re-renders and improve performance.

B
Bootspring Team
Engineering
March 25, 2021
7 min read

Context causes re-renders for all consumers on any change. Here's how to optimize with selectors.

The Problem#

Loading code block...

Solution 1: Split Contexts#

Loading code block...

Solution 2: Selector Hook with useSyncExternalStore#

Loading code block...

Solution 3: Context with Ref and Subscription#

Loading code block...

Solution 4: Memoized Context Value#

Loading code block...

Solution 5: Higher-Order Component Selector#

Loading code block...

Zustand-Style Implementation#

Loading code block...

Performance Comparison#

Loading code block...

Best Practices#

Strategies: ✓ Split contexts by update frequency ✓ Use selectors for granular subscriptions ✓ Memoize context values ✓ Consider external state libraries Performance: ✓ Keep selectors simple ✓ Return primitive values when possible ✓ Use shallow comparison ✓ Avoid creating objects in selectors Libraries: ✓ Zustand for simple state ✓ Jotai for atomic state ✓ use-context-selector for existing contexts ✓ React Query for server state

Conclusion#

Context selectors prevent unnecessary re-renders by subscribing to specific state slices. Split contexts for different domains, use useSyncExternalStore for selector patterns, or adopt libraries like Zustand. The right approach depends on your app's complexity and update patterns.

Share this article

Help spread the word about Bootspring

Related articles