Skip to content

Store Performance Patterns

Comprehensive guide to optimizing store performance in Context-Action applications. This overview covers all major performance optimization categories.

Performance Categories

Memoization Patterns

Optimization patterns using React's memoization hooks to prevent unnecessary re-renders and expensive computations:

  • Stable Selectors: Using useCallback for consistent selector functions
  • Complex Selector Memoization: Optimizing data transformations
  • Computed Store Dependencies: Memoizing expensive computation functions

Batching Patterns

Patterns for batching multiple store updates to prevent unnecessary re-renders:

  • Store Update Batching: Using React's unstable_batchedUpdates
  • Store Batch API: Leveraging built-in batch methods
  • Atomic Operations: Grouping related updates together

Subscription Optimization

Optimize store subscriptions to reduce unnecessary re-renders:

  • Selective Subscriptions: Subscribe only to needed data
  • Conditional Subscriptions: Subscribe only when necessary
  • Debounced Subscriptions: Handle fast-changing data efficiently

Comparison Strategies

Choose the right comparison strategy to balance performance and accuracy:

  • Reference Comparison: Fastest for primitives and managed references
  • Shallow Comparison: Balanced approach for objects
  • Deep Comparison: Most accurate for nested structures
  • Custom Comparison: Business logic specific comparisons
  • Circular Reference Safety: Handle complex object structures

Lazy Evaluation Patterns

Defer expensive operations and access values only when needed:

  • Lazy State Access: Get current state at execution time
  • Conditional Store Access: Access stores only when conditions are met
  • Deferred Calculations: Postpone expensive computations
  • Lazy Loading: Load data on demand

Memory Management

Prevent memory leaks and manage resources efficiently:

  • Event Object Prevention: Avoid storing DOM events
  • Subscription Cleanup: Proper cleanup of manual subscriptions
  • Cross-Platform Timeouts: Handle timeouts safely across environments
  • Weak References: Use WeakMap/WeakSet for large data

Debugging & Development

Development tools and debugging patterns:

  • Debug Mode: Enable debugging for store value changes
  • Performance Monitoring: Track store update metrics
  • State Inspection: Debug multiple stores simultaneously
  • Development Utilities: Custom debugging tools

Error Handling & Recovery

Robust error handling and recovery patterns:

  • Centralized Error Handling: Use framework's error system
  • EventBus Memory Safety: Safe event handling patterns
  • Graceful Degradation: Provide fallback strategies
  • Retry Mechanisms: Handle transient failures

Quick Reference

Performance Priority Matrix

PriorityPattern CategoryImpactComplexity
HighMemory Management🔴 Critical⚡ Low
HighMemoization Patterns🟠 Major⚡⚡ Medium
MediumSubscription Optimization🟠 Major⚡⚡ Medium
MediumBatching Patterns🟡 Moderate⚡ Low
MediumComparison Strategies🟡 Moderate⚡⚡ Medium
LowLazy Evaluation Patterns🟡 Moderate⚡⚡⚡ High
DevelopmentDebugging & Development🔵 Development⚡ Low
FoundationError Handling & Recovery🔴 Critical⚡⚡ Medium

Common Performance Issues

  1. Memory LeaksMemory Management
  2. Excessive Re-rendersMemoization Patterns
  3. Inefficient SubscriptionsSubscription Optimization
  4. Slow ComparisonsComparison Strategies
  5. Unnecessary WorkLazy Evaluation Patterns

Implementation Strategy

Phase 1: Foundation (Critical)

  1. Memory Management - Prevent leaks
  2. Error Handling & Recovery - Robust error handling

Phase 2: Core Optimization (High Impact)

  1. Memoization Patterns - Reduce re-renders
  2. Subscription Optimization - Efficient subscriptions

Phase 3: Fine-tuning (Medium Impact)

  1. Batching Patterns - Batch updates
  2. Comparison Strategies - Optimize comparisons

Phase 4: Advanced (Situational)

  1. Lazy Evaluation Patterns - Defer work
  2. Debugging & Development - Development tools

Best Practices Summary

✅ Universal Do's

  • Use useCallback for stable selectors
  • Extract data from DOM events instead of storing event objects
  • Use framework's centralized error handling system
  • Choose appropriate comparison strategies
  • Enable debug mode in development only

❌ Universal Avoid's

  • Creating new functions in selectors on every render
  • Storing DOM events or React synthetic events in stores
  • Using direct console.error instead of centralized error handling
  • Deep comparisons unless absolutely necessary
  • Ignoring subscription cleanup

Architecture Integration

Immer and Comparison System

Context-Action uses a dual-layer optimization system:

  • Immer Layer: Safe immutable updates with Copy-on-Write optimization
  • Comparison Layer: Change detection and re-render optimization

Why both are needed:

  • Immer: Prevents mutation bugs, ensures safe copies
  • Comparison: Prevents unnecessary re-renders, optimizes performance

Key insight: Immer handles immutability, comparison handles change detection. They solve different problems and work together.

For detailed technical information, see:

Performance Impact

SystemPerformance BenefitWhen Active
Immer Copy-on-WriteAvoid unnecessary object creationIndividual store updates
Comparison OptimizationSkip re-renders for identical valuesIndividual store setValue() calls
Combined SystemMaximum efficiencyEach store operates independently

Released under the Apache-2.0 License.