CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mobx-react-lite

Lightweight React bindings for MobX based on React 16.8+ and Hooks

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

advanced.mddocs/

Advanced Features

Advanced configuration and utilities including observer batching, memory management, and deprecated APIs for migration purposes. These features provide fine-grained control over MobX React Lite behavior and compatibility.

Capabilities

Observer Batching

Controls how MobX reactions are scheduled and batched with React's update mechanisms. This ensures optimal performance by coordinating MobX updates with React's batching system.

/**
 * Configures MobX reaction scheduler for batching updates with React
 * @param reactionScheduler - Batching function, typically from React DOM or React Native
 */
function observerBatching(reactionScheduler: any): void;

Usage Examples:

import { observerBatching } from "mobx-react-lite";
import { unstable_batchedUpdates } from "react-dom";

// Manual batching configuration (usually automatic)
observerBatching(unstable_batchedUpdates);

// React Native batching
import { unstable_batchedUpdates } from "react-native";
observerBatching(unstable_batchedUpdates);

// Custom batching function
observerBatching((callback) => {
  // Custom batching logic
  console.log("Batching MobX reaction");
  callback();
});

// Disable batching (not recommended)
observerBatching(null);

Observer Batch Status (Deprecated)

Returns whether observer batching is enabled. This function is deprecated and always returns true.

/**
 * @deprecated Always returns true
 * Returns whether observer batching is enabled
 * @returns Always true in current implementation
 */
function isObserverBatched(): boolean;

Memory Management

Utilities for managing internal timers and finalization registry used by the observer system.

/**
 * Clears internal finalization timers immediately
 * Useful for testing or manual memory management
 */
function clearTimers(): void;

Usage Examples:

import { clearTimers } from "mobx-react-lite";

// Clear timers in test cleanup
afterEach(() => {
  clearTimers();
});

// Manual cleanup before app shutdown
window.addEventListener("beforeunload", () => {
  clearTimers();
});

// In test environments
if (process.env.NODE_ENV === "test") {
  // Clear timers between tests to prevent interference
  beforeEach(() => {
    clearTimers();
  });
}

Deprecated useObserver Hook

Low-level hook that provides observer functionality with manual control. This is deprecated in favor of the observer HOC or <Observer> component.

/**
 * @deprecated Use <Observer>{fn}</Observer> instead or wrap component with observer
 * Manually creates an observer region within a component
 * @param fn - Function to track for observable access
 * @param baseComponentName - Name for debugging purposes
 * @returns Result of the tracked function
 */
function useObserver<T>(fn: () => T, baseComponentName?: string): T;

Migration Examples:

// Old approach (deprecated)
const MyComponent = () => {
  const store = useStore();
  
  return useObserver(() => (
    <div>
      <h1>{store.title}</h1>
      <p>{store.description}</p>
    </div>
  ), "MyComponent");
};

// New approach with Observer component
const MyComponent = () => {
  const store = useStore();
  
  return (
    <Observer>
      {() => (
        <div>
          <h1>{store.title}</h1>
          <p>{store.description}</p>
        </div>
      )}
    </Observer>
  );
};

// Best approach with observer HOC
const MyComponent = observer(() => {
  const store = useStore();
  
  return (
    <div>
      <h1>{store.title}</h1>
      <p>{store.description}</p>
    </div>
  );
});

Internal Implementation Details

Batching Files

MobX React Lite provides several batching configuration files for different environments:

  • batchingForReactDom.js - React DOM batching configuration
  • batchingForReactNative.js - React Native batching configuration
  • batchingOptOut.js - Disables batching entirely

These files can be imported directly to configure batching behavior:

// Import specific batching configuration
import "mobx-react-lite/batchingForReactDom";

// Or for React Native
import "mobx-react-lite/batchingForReactNative";

// Or to opt out of batching
import "mobx-react-lite/batchingOptOut";

Development vs Production

Several features behave differently in development vs production:

  • Deprecation warnings: Only shown in development mode
  • PropTypes validation: Only active in development for Observer component
  • Debug information: Additional debugging info available in development
  • Error messages: More detailed error messages in development
// Development-only warnings example
if (process.env.NODE_ENV !== "production") {
  console.warn("[mobx-react-lite] Development warning message");
}

Important Notes

Batching Behavior

  • Automatic configuration: MobX React Lite automatically configures batching on import
  • React 18 compatibility: Works with both legacy and concurrent React features
  • Custom schedulers: Advanced users can provide custom batching functions
  • Performance impact: Proper batching significantly improves performance with multiple observable changes

Memory Management

  • Automatic cleanup: Components automatically clean up reactions on unmount
  • Finalization registry: Modern browsers use FinalizationRegistry for additional cleanup
  • Manual control: clearTimers() provides manual control over cleanup timing
  • Test environments: Important to clear timers between tests to prevent interference

Migration Path

For codebases upgrading from older versions:

  1. Replace useObserver: Convert useObserver calls to <Observer> component or observer HOC
  2. Update useLocalStore: Migrate from useLocalStore to useLocalObservable
  3. Remove useAsObservableSource: Replace with useEffect synchronization pattern
  4. Update static rendering: Use enableStaticRendering instead of useStaticRendering

Performance Optimization

  • Batching: Ensure proper batching configuration for your React environment
  • Memory cleanup: Use clearTimers() in test environments to prevent memory leaks
  • Observer granularity: Use <Observer> for fine-grained reactive regions in large components
  • Static rendering: Enable static rendering for SSR to avoid unnecessary server-side reactions

docs

advanced.md

index.md

local-state.md

observers.md

static-rendering.md

tile.json