Search code examples
reactjsreact-hooksmicro-frontendwebpack-module-federation

Module Federation | Invalid hook call. Hooks can only be called inside of the body of a function component


I am trying to consume react component remotely, which has just simple counter app (useState). And Host app which is with React and Redux.

Remote is working fine as an isolated app, but when it is consumed by host getting below error

enter image description here

react-dom.production.min.js:209 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

What i tried:

here is my webpack config

[remote]

 new ModuleFederationPlugin({
      name: 'RemoteMap',
      filename: 'Remote.js',

      exposes: {
        './Bootstrap': resolvePath(process.cwd(), 'src/common/components/organisms/remote/index.tsx')
      },
      shared: {

        "react": {
          eager: true,
          singleton: true,
          strictVersion: true,
          requiredVersion: dependencies.react
        },
        "react-redux": {
          eager: true,
          singleton: true
        },
        'react-dom': {
          eager: true,
          singleton: true
        }
      }
    })

[Host]

 new ModuleFederationPlugin({
      name: 'Host',
      remotes: {
        // remote: ,
        myApp: 'RemoteMap@http://localhost:8081/Remote.js'
      }
    }),

What could be the possible reasons and fix for above error. ?


Solution

  • I had the same problem configuring the host with React. To resolve I added the dependencies as shared:

    const packageJson = require('./package.json');
    
    ...
    
    new ModuleFederationPlugin({
        name: "App",
        remotes: {
          HomeApp: "HomeApp@http://localhost:9002/remoteEntry.js",
          ContactApp: "ContactApp@http://localhost:9003/remoteEntry.js",
          //HomeApp: lazyLoadRemote("http://localhost:9002/remoteEntry.js","HomeApp"),
          //ContactApp: lazyLoadRemote("http://localhost:9003/remoteEntry.js","ContactApp"),
        },
        shared: {...packageJson.devDependencies}
      }),