'React context between microfrontends

TLDR; How to use a single context between react micro frontends?

The application is divided into multiple Microfrontends or react apps. Each of these is running on a different port. A container is hosting other Micrfrontends. Each one is a separate react app and it is a runtime integration. (I have used martinfowler example to implement micro frontend)

Currently passing some data via URL and browser storage (localStorage/cookies) to other Microfrontends.

I need to pass the data across these react apps (MFEs) using React Context.

I have defined ReactContext Provider in Container (ReactApp1) and stored value (say color=black). To access this color inside the lower level Microfrontend (ReactApp2) we need the context to be available from any micro frontend. How to make it available?

(NOTE: I don't want to use localStorage or cookies for global data sharing)

<Container>
  <LowerLevelMFE1/>
  <LowerLevelMFE2/>
  ...
</Container>


Solution 1:[1]

I think sharing context between Micro-frontends is an anti-pattern and should be avoided if you can. If you use context to share data, you will automatically couple the MFes that depend on the context, eliminating the benefits of independent deployments by introducing coordination and a dependency.

My advice is that each micro-frontend loads the data they need and if there is communication need it, you need an api or a contract to handle this communication.

Solution 2:[2]

I think if you need that type of comunication between the mfe's then they are splited wrong.

As Ruben says, is an anti pattern.

Solution 3:[3]

Webpack 5's Module Federation & ModuleFederationPlugin is the best way I've found to achieve this architectural pattern.

In essence you create a "host" application that wraps the React.context around a "remote" component. This "remote" is actually another component in a standalone application that is being exposed as a remote through its webpack config file. In this 2nd application you would consume the context as normal using React.useContext.

You can find a full example of this setup here on github.

A few things to note:

  1. Both applications will need to consume this Context's source code so moving it into its own package is preferred.
  2. Your Context consuming application will still need, what I call in MFEs, "developer scaffolding". In this case that would be a simple component that wraps your <ContextConsumer /> in a <ContextProvider /> that you are importing from your shared Context package I mentioned in 1.
    • Remember this app with scaffolding is only exposing the <ContextConsumer /> which you need to make sure to specify in the webpack config.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ruben Casas
Solution 2 Marcos
Solution 3 jpkiser