CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mobx-react

React bindings for MobX that enable the creation of fully reactive React components.

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

hooks-utilities.mddocs/

Hooks and Utilities

Modern React hooks and utilities from mobx-react-lite, plus legacy lifecycle management utilities for class components.

Capabilities

Local Observable Hook

Hook to create local observable state within functional components.

/**
 * Creates local observable state within functional components
 * @param initializer - Function that returns the initial observable state
 * @returns Observable state object
 */
function useLocalObservable<T>(initializer: () => T): T;

Usage Example:

import React from "react";
import { observer, useLocalObservable } from "mobx-react";

const Counter = observer(() => {
  const store = useLocalObservable(() => ({
    count: 0,
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
    get doubled() {
      return this.count * 2;
    }
  }));

  return (
    <div>
      <p>Count: {store.count}</p>
      <p>Doubled: {store.doubled}</p>
      <button onClick={store.increment}>+</button>
      <button onClick={store.decrement}>-</button>
    </div>
  );
});

Observable Source Hook

Hook to convert props to observable source, useful for creating reactive computations based on props.

/**
 * Converts props to observable source for reactive computations
 * @param source - Object to convert to observable source
 * @returns Observable version of the source object
 */
function useAsObservableSource<T>(source: T): T;

Usage Example:

import React from "react";
import { observer, useAsObservableSource, useLocalObservable } from "mobx-react";
import { computed } from "mobx";

const UserProfile = observer(({ userId, userName }) => {
  const observableProps = useAsObservableSource({ userId, userName });
  
  const store = useLocalObservable(() => ({
    get displayName() {
      return `User: ${observableProps.userName} (ID: ${observableProps.userId})`;  
    },
    get isValidUser() {
      return observableProps.userId > 0 && observableProps.userName.length > 0;
    }
  }));

  return (
    <div>
      <h1>{store.displayName}</h1>
      {store.isValidUser ? "Valid user" : "Invalid user"}
    </div>
  );
});

Local Store Hook (Deprecated)

Hook to create local observable store with computed values and actions.

/**
 * @deprecated Use useLocalObservable instead
 * Creates local observable store with computed values and actions
 * @param initializer - Function that returns the initial store state
 * @returns Observable store object
 */
function useLocalStore<TStore extends Record<string, any>>(initializer: () => TStore): TStore;

/**
 * @deprecated Use useLocalObservable instead
 * Creates local observable store with source object dependency
 * @param initializer - Function that receives source and returns the initial store state
 * @param current - Source object to pass to initializer
 * @returns Observable store object
 */
function useLocalStore<TStore extends Record<string, any>, TSource extends object>(
  initializer: (source: TSource) => TStore,
  current: TSource
): TStore;

Observer Component

Component wrapper for creating reactive regions without wrapping the entire component.

/**
 * Component wrapper for reactive regions
 * @param children - Function that returns JSX to be made reactive  
 * @returns Reactive JSX element
 */
function Observer({ children }: { children: () => React.ReactNode }): JSX.Element;

Usage Example:

import React from "react";
import { Observer } from "mobx-react";

function App({ store }) {
  return (
    <div>
      <h1>My App</h1>
      <Observer>
        {() => <p>Count: {store.count}</p>}
      </Observer>
      <button onClick={() => store.increment()}>
        Increment
      </button>
    </div>
  );
}

Static Rendering

Functions to control server-side rendering behavior.

/**
 * Enables or disables static rendering mode for server-side rendering
 * @param enable - Whether to enable static rendering
 */
function enableStaticRendering(enable: boolean): void;

/**
 * Checks if static rendering mode is currently enabled
 * @returns True if static rendering is enabled
 */
function isUsingStaticRendering(): boolean;

/**
 * @deprecated Use enableStaticRendering instead
 * Legacy function to control static rendering
 * @param enable - Whether to enable static rendering
 */
function useStaticRendering(enable: boolean): void;

Usage Example:

// In your server-side rendering setup
import { enableStaticRendering } from "mobx-react";

// Enable static rendering for SSR
enableStaticRendering(true);

// In your client-side entry point
import { enableStaticRendering } from "mobx-react";

// Disable static rendering for client-side
enableStaticRendering(false);

Observer Batching

Functions to configure batching behavior for observer updates.

/**
 * Configures observer batching behavior
 * @param batchFunction - Function to use for batching updates
 */
function observerBatching(batchFunction: (callback: () => void) => void): void;

/**
 * Checks if observer batching is currently enabled
 * @returns True if batching is enabled
 */
function isObserverBatched(): boolean;

Usage Example:

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

// Configure custom batching
observerBatching(unstable_batchedUpdates);

Dispose on Unmount (Deprecated)

Decorator and function for automatic disposal of MobX reactions when class components unmount.

/**
 * @deprecated Not compatible with React 18 and higher
 * Decorator for automatic disposal when component unmounts
 * @param target - Component instance
 * @param propertyKey - Property key to dispose
 */
function disposeOnUnmount(target: React.Component<any, any>, propertyKey: PropertyKey): void;

/**
 * @deprecated Not compatible with React 18 and higher  
 * Function for automatic disposal when component unmounts
 * @param target - Component instance
 * @param fn - Disposer function or array of disposer functions
 * @returns The disposer function(s)
 */
function disposeOnUnmount<TF extends Disposer | Array<Disposer>>(
  target: React.Component<any, any>,
  fn: TF
): TF;

type Disposer = () => void;

Usage Example:

import React from "react";
import { observer, disposeOnUnmount } from "mobx-react";
import { autorun } from "mobx";

@observer
class TodoList extends React.Component {
  @disposeOnUnmount
  autorunDisposer = autorun(() => {
    console.log(`Todo count: ${this.props.store.todos.length}`);
  });

  componentDidMount() {
    // Alternative function syntax
    const disposer = autorun(() => {
      console.log("Another autorun");
    });
    disposeOnUnmount(this, disposer);
  }

  render() {
    return <div>{/* Component content */}</div>;
  }
}

External Batching Configuration

mobx-react provides separate entry point files for configuring batching behavior:

  • mobx-react/batchingForReactDom - Configures batching optimized for ReactDOM
  • mobx-react/batchingForReactNative - Configures batching optimized for React Native
  • mobx-react/batchingOptOut - Disables batching completely

Usage Example:

// Configure for ReactDOM (typically at app entry point)
import "mobx-react/batchingForReactDom";

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

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

Types

type Disposer = () => void;

docs

hooks-utilities.md

index.md

reactivity.md

store-management.md

validation.md

tile.json