Back to Blog
ReactContextPerformanceOptimization

Optimizing React Context Performance

Avoid Context performance pitfalls. From splitting contexts to memoization to selector patterns.

B
Bootspring Team
Engineering
August 8, 2021
6 min read

React Context can cause unnecessary re-renders. Here's how to optimize it.

The Problem#

Loading code block...

Solution 1: Split Contexts#

Loading code block...

Solution 2: Separate State and Dispatch#

Loading code block...

Solution 3: Memoize Context Value#

Loading code block...

Solution 4: Selector Pattern#

Loading code block...

Solution 5: Component Composition#

Loading code block...

Solution 6: Ref for Non-Reactive State#

Loading code block...

Measuring Performance#

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles