Module Federation - React TypeError: Cannot read properties of null (reading 'useState')

Issue

I’m having this error with React version 19.0.0 when I try to load a MFE with Rsbuild and module federation plugin

React TypeError: Cannot read properties of null (reading 'useState')

Solution

There can be many reasons causing this issue. The most common ones are:

  1. react and react-dom have different versions. To fix this, make sure that they have the same version in package.json and package-lock.json
  2. Two instances of react are loaded. This is caused by the microfrontend loading, and can be fixed by updating the Rsbuild module federation settings. You should configure react and react-dom as a shared dependency and set singleton to true to ensure React is only loaded once when the microfrontend is imported.

Here is an example of rsbuild.config.ts file

import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginModuleFederation({
      name: 'app_name',
      remotes: {
        //remote config here
      },
      shared: {
        react: {
          singleton: true,
        },
        'react-dom': {
          singleton: true,
        },
      },
    }),
  ],
});

When you enable singleton moode, the shared dependencies between the remote modules and the host application will only be loaded once. If different versions are present, the higher version will be loaded and a warning will be given for the module with the lower version.

This is also documented in rspack module-federation-plugin documentation:

singleton: Ensure that shared modules are only loaded once between different versions, following the singleton pattern. This is necessary for libraries designed to run as singletons, such as React, as it can prevent various issues caused by instantiating multiple library instances.