Safely render dynamic remote React apps with Module Federation
How can we use Webpack Module Federation’s Dynamic Remote Containers in a React micro frontend app safely, easily and performantly?
Lets start with a vision of what we want:
RemoteComponent is a React component we can use throughout our application to render modules from a remote app. It encapsulates:
ErrorBoundaryto safely render remote code without breaking our host app.
- Lazy loading to resolve the remote code as needed without blocking the rest of our app rendering.
- Fetching and managing dynamic remote containers.
Here is the implementation:
We are lazy loading the
Component we get back from
loadComponent() and wrapping it around an
ErrorBoundary to prevent the entire application from crashing if something goes wrong. We are also using a
React.Suspense to optionally render a loading indicator while the remote app is being fetched.
The URL for our remote apps is managed using a
useRemoteUrl() hook. The details of the hook aren’t important for this example but you could implement the URL management a number of different ways depending on your use case. The important piece is that we are able to get a URL to pass to the
loadComponent utility that manages the remote containers:
We only load the remote app once even if we reuse components from it throughout our application. It is important that the container we fetch matches the
get/init interface expected by Module Federation. This works best if the remote app’s Webpack is already configured using the Module Federation plugin.
fetchRemote() handles fetching the remote app’s
Voila! We have a mechanism for reliably fetching and rendering remote apps within our React micro frontend.
Now lets see it in action:
A live example of this approach can be found here: https://micro-frontend-demo-main.vercel.app/
Source code: link
For an intro on using Module Federation in React checkout one of my other posts: