Member-only story
Zustand in a Micro Frontend
State management made simple.
As you develop a large-scale Micro Frontend application built using Webpack’s Module Federation, you will eventually need to share data and communicate between your micro-apps. I will cover the many options available in later articles but first I want to share with you an example of using a state management solution.
Note: Sharing global state in a Micro Frontend architecture should be a last resort and carefully designed as it introduces unnecessary coupling between your teams.
Zustand is a relatively new state management tool still early in its lifecycle with only ~470k weekly downloads, but it has been picking up steam rapidly. It is an elegant and fun-to-use solution I urge you to try.
How could we build a Zustand store that we can use across our micro apps?
Creating a shared Zustand store
First, we need to instantiate a Zustand store in one of our micro-apps. It can be any that exposes remote modules with Module Federation.
In this example, we have a store tracking some form of cart with methods to add or remove items from the cart.
Notice we instantiated the store by creating a useStore
hook. This is what we will expose to the other apps.
Next, we update our webpack.config.js
:
Now we’re ready to use the store in our other micro apps: