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

observers.mddocs/

Component Observers

Core functionality for making React components reactive to MobX observable changes. The observer pattern automatically tracks observable access during render and triggers re-renders when any accessed observables change.

Capabilities

Observer Function

Higher-order component that wraps functional components to make them reactive to MobX observables. Automatically applies React.memo for performance optimization.

/**
 * Converts a React functional component into a reactive component
 * @param baseComponent - The functional component to make reactive
 * @param options - Optional configuration for forwardRef behavior
 * @returns Reactive component that re-renders when observables change
 */
function observer<P extends object>(
  baseComponent: React.FunctionComponent<P>,
  options?: IObserverOptions
): React.FunctionComponent<P>;

// ForwardRef support
function observer<P extends object, TRef = {}>(
  baseComponent: React.ForwardRefRenderFunction<TRef, P>,
  options: IObserverOptions & { forwardRef: true }
): React.MemoExoticComponent<
  React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
>;

// ForwardRefExoticComponent support  
function observer<P extends object, TRef = {}>(
  baseComponent: React.ForwardRefExoticComponent<
    React.PropsWithoutRef<P> & React.RefAttributes<TRef>
  >
): React.MemoExoticComponent<
  React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
>;

interface IObserverOptions {
  readonly forwardRef?: boolean;
}

Usage Examples:

import { observer } from "mobx-react-lite";
import { observable } from "mobx";

// Basic observer component
const UserProfile = observer(({ userId }: { userId: string }) => {
  const store = useUserStore();
  const user = store.getUser(userId);
  
  return (
    <div>
      <h1>{user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
});

// Observer with forwardRef
const FancyInput = observer(React.forwardRef<HTMLInputElement, Props>(
  ({ value, onChange }, ref) => {
    return <input ref={ref} value={value} onChange={onChange} />;
  }
));

// Alternative forwardRef syntax (deprecated)
const FancyInputAlt = observer(
  (props: Props, ref: React.Ref<HTMLInputElement>) => {
    return <input ref={ref} {...props} />;
  },
  { forwardRef: true }
);

Observer Component

React component that applies observer behavior to an anonymous region within your component. Can be used inside both class and function components.

/**
 * React component that makes its children reactive to observable changes
 * @param props - Component props with children or render function
 * @returns Reactive region that re-renders when observables change
 */
function Observer(props: IObserverProps): React.ReactElement | null;

interface IObserverProps {
  /** Function returning React element to render */
  children?(): React.ReactElement | null;
  /** Alternative render function (same as children) */
  render?(): React.ReactElement | null;
}

Usage Examples:

import { Observer } from "mobx-react-lite";
import { observable } from "mobx";

// Using Observer with children function
const App = () => {
  const [store] = useState(() => observable({ count: 0 }));
  
  return (
    <div>
      <h1>My App</h1>
      <Observer>
        {() => <div>Reactive count: {store.count}</div>}
      </Observer>
      <button onClick={() => store.count++}>
        Increment
      </button>
    </div>
  );
};

// Using Observer with render prop
const Dashboard = () => {
  const store = useStore();
  
  return (
    <div>
      <Observer render={() => 
        <div className={store.theme}>
          User: {store.currentUser.name}
        </div>
      } />
    </div>
  );
};

// Using Observer inside class components
class LegacyComponent extends React.Component {
  render() {
    return (
      <div>
        <Observer>
          {() => <div>Reactive data: {this.props.store.data}</div>}
        </Observer>
      </div>
    );
  }
}

Important Notes

Observer Behavior

  • Automatic tracking: Observer automatically tracks which observables are accessed during render
  • Batched updates: Updates are batched using React's built-in batching mechanisms
  • Memory management: Reactions are automatically disposed when components unmount
  • Error boundaries: Exceptions during rendering are properly re-thrown to error boundaries
  • Static rendering: In SSR mode, observer components render normally without creating reactions

Common Patterns

  • Wrap entire components: Use observer() to wrap your entire functional component
  • Selective observation: Use <Observer> for specific reactive regions within larger components
  • Avoid double wrapping: Don't wrap observer components with React.memo (observer already applies memo)
  • ForwardRef integration: Use React.forwardRef() directly rather than the deprecated forwardRef option

Performance Considerations

  • Observer automatically applies React.memo with shallow comparison
  • Only components that access observables during render will re-render
  • Unused observables won't trigger re-renders even if they change
  • Observers batch updates automatically for optimal performance

docs

advanced.md

index.md

local-state.md

observers.md

static-rendering.md

tile.json