Vite - React TypeError: Cannot read properties of null (reading 'useState')
Issue
Hi, I’m having an error when I try to load a microfrontend with Vite and module federation plugin. react and react-dom versions are aligned on version 19, and versions of parent UI and MFE’s react are aligned as well
React TypeError: Cannot read properties of null (reading 'useState')
How can I fix this?
Solution
This is probably because the two instances of react
are loaded, one is from the remote MFE and the other one is from the host loading the MFE. You can fix it by updating Vite configuration and setting singleton: true
. It is also highly suggested to add requiredVersion
parameter to guarantee that the version of the MFE is compatible with the host UI
Here is an example of vite.config.ts
file
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { federation } from "@module-federation/vite";
import { dependencies } from "./package.json";
export default defineConfig({
plugins: [
react(),
federation({
name: "remote_app_name",
filename: "remoteEntry.js",
exposes: {
"./ExposedComponent": "./src/components/ExposedComponent.tsx",
},
shared: {
react: { requiredVersion: dependencies.react, singleton: true },
"react-dom": {
requiredVersion: dependencies["react-dom"],
singleton: true,
},
"react-router": {
requiredVersion: dependencies["react-router"],
singleton: true,
},
},
}),
],
build: {
target: "esnext",
rollupOptions: {
output: {
assetFileNames() {
return "[name][extname]";
},
},
},
},
});
Optionally, instead of setting requiredVersion
, you can try setting import: false
, this will guarantee that react dependency is packaged in the remote MFE build, forcing the module to use the host react version