DMF React Package

The @dream.mf/react package provides React-specific utilities and components for Dream Packages applications, including error boundaries, state management hooks, and module federation utilities.

Installation

npm install @dream.mf/react
# or
yarn add @dream.mf/react

Components

ErrorBoundary

A React error boundary component that catches JavaScript errors anywhere in the child component tree and displays a fallback UI instead of the component tree that crashed.

Props

Prop Type Required Description
children ReactNode Yes The components to be rendered and monitored for errors
fallback ReactElement No Custom error UI to display when an error occurs. If not provided, a default error message will be shown

Example

import { ErrorBoundary } from '@dream.mf/react';

function App() {
  return (
    <ErrorBoundary 
      fallback={<div>Something went wrong. Please try again.</div>}
    >
      <YourComponent />
    </ErrorBoundary>
  );
}

Features

  • Catches runtime errors in child components
  • Prevents the entire app from crashing
  • Supports custom error UI through the fallback prop
  • Logs errors to the console with component stack traces

Hooks

useStatePromise

An enhanced version of React's useState that returns a Promise-based setState function. This is useful when you need to perform actions after the state has been updated.

Type Definition

type SetStatePromise<T> = (newValue: T) => Promise<void>;
function useStatePromise<T>(initialValue: T): [T, SetStatePromise<T>];

Parameters

  • initialValue: T - The initial state value of type T

Returns

  • [T, SetStatePromise<T>] - A tuple containing:
    • Current state value of type T
    • Promise-based setState function that resolves after the state update

Example

import { useStatePromise } from '@dream.mf/react';

function AsyncComponent() {
  const [value, setValue] = useStatePromise<string>('');

  const handleAsyncUpdate = async () => {
    await setValue('new value');
    // This code will run after the state is actually updated
    console.log('State has been updated!');
  };

  return (
    <div>
      <p>Current value: {value}</p>
      <button onClick={handleAsyncUpdate}>Update Value</button>
    </div>
  );
}

Module Federation Types

ImportRemoteOptions

Configuration for importing remote modules.

interface ImportRemoteOptions {
  remoteName: string;
  scope: string;
  module: string;
  remoteUrl?: string;
  bustRemoteEntryCache?: boolean;
}

LoadRemoteOptions

Configuration for loading remote modules.

interface LoadRemoteOptions {
  url: string;
  scope: string;
  bustRemoteEntryCache?: boolean;
}

WebpackContainerScope

Type definition for webpack module federation container scope.

interface WebpackContainerScope {
  __initialized: boolean;
  __initializing: boolean;
  init(scopes: unknown): Promise<Record<string, unknown>>;
}

Example Usage

Error Boundary with Custom Fallback

import { ErrorBoundary } from '@dream.mf/react';

function ErrorFallback({ error }) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <pre>{error.message}</pre>
    </div>
  );
}

function App() {
  return (
    <ErrorBoundary fallback={<ErrorFallback />}>
      <YourComponent />
    </ErrorBoundary>
  );
}

Async State Management

import { useStatePromise } from '@dream.mf/react';

function UserProfile() {
  const [userData, setUserData] = useStatePromise(null);

  const loadUserData = async () => {
    try {
      await setUserData(fetchedData);
      // This code runs after state is updated
      console.log('User data loaded successfully');
    } catch (error) {
      console.error('Failed to load user data');
    }
  };

  return (
    <div>
      {userData ? (
        <UserInfo data={userData} />
      ) : (
        <LoadingSpinner />
      )}
    </div>
  );
}

Module Federation Setup

import { WebpackContainerScope } from '@dream.mf/react';

const loadRemoteModule = async ({
  remoteName,
  scope,
  module,
  remoteUrl
}: ImportRemoteOptions) => {
  // Implementation for loading remote modules
  const container = window[scope] as WebpackContainerScope;
  await container.init({});
  const factory = await container.get(module);
  return factory();
};