Recoil Duplicate atom key when using with Webpack Module Federation

Viewed 1175

I'm using Webpack Module Federation to create 2 React applications: host and child.

In the host, I create atoms.ts and selector.ts filed and I expose them via the plugin under the expose section:

  exposes: {
    "./atoms": "./src/recoil/atoms.ts",
    "./selectors": "./src/recoil/selectors.ts",
  }

Inside the child, I just consume that via the remotes section:

  remotes: {
    host: "host@http://localhost:3000/remoteEntry.js",
  }

Then, in the code of the child I use that like that:

import {someSelector} from "host/selectors"
const val = useRecoilValue(someSelector);

It's working fine but I got this warning in the console:

Duplicate atom key "userAuthState". This is a FATAL ERROR in
      production. But it is safe to ignore this warning if it occurred because of
      hot module replacement.

Does anyone face that issue and know if it's really a problem or how we could hide the warning?

Another related q: Is it ok that the host will contain <RecoilRoot> and also the child will contain <RecoilRoot> ? because I want both will manage their own state but also share atom/selectors.

Thanks!

3 Answers

Regarding your second question: Yes, this is totally fine. The nested <RecoilRoot> will create its own context and every atom referenced below the second root will be independent from the upper root. This is also explained in the docs.

Regarding the first question: As the log states this is fine as long as it occurs during development. Sometimes during the hot module replacement recoil throws away atoms and reinstantiates them causing this duplication to happen internally.

But as long as this warning doesn't pop up in your production code, everything is fine.

Are you importing the atoms or the selectors in your host application using a local path?

You need to include in your host webpack config its own entrypoint as remote and import your atoms from 'host/atoms'

I think this could solve your issue.

You can ignore the warning output (if you can bare it), functionality is not affected.

Also, you can install the intercept-stdout package and add the following to next.config.js (outside of the exported configuration):

const intercept = require("intercept-stdout") 
// safely ignore recoil warning messages in dev (triggered by HMR)

function interceptStdout(text) {
  if (text.includes("Duplicate atom key")) {
    return "";
  }
  return text;
}

if (process.env.NODE_ENV === "development") {
  intercept(interceptStdout);
}

This way can omit the annoying warning in console.

Related