Rsbuild, error loading module - Cannot read properties of null (reading 'useState')
Issue
When I try to load a microfrontend using Rsbuild with the module federation plugin and React version 19.0.0
, the following error occurs:
React TypeError: Cannot read properties of null (reading 'useState')
</div>
Solution
Probably, the issue arises because two separate instances of react
are being loaded—one by the host application and another by the microfrontend. This conflict can be resolved by updating the Rsbuild module federation configuration.
To fix this, configure react
and react-dom
as shared dependencies and set the singleton
property to true
. This ensures that React is only loaded once across the host and microfrontend.
Below is an example configuration for the 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 the singleton mode, shared dependencies between the host application and remote modules are loaded only once. If multiple versions of a dependency are detected, the highest version is used, and a warning is issued for the lower version.
For more details, refer to the documentation for the rspack
module-federation-plugin.
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.