How to share redux store in micro frontend architecture? How to share redux store in micro frontend architecture? reactjs reactjs

How to share redux store in micro frontend architecture?


There is a comment in the article addressing this directly:

If you are using redux, the usual approach is to have a single, global, shared store for the entire application. However, if each micro frontend is supposed to be its own self-contained application, then it makes sense for each one to have its own redux store. The redux docs even mention "isolating a Redux app as a component in a bigger application" as a valid reason to have multiple stores.

Long story short: Don't share your redux store

Sharing anything between your micro frontends no longer makes them separate entities and defeats the entire purpose of it. Now it's just an overengineered monolith. Just turn those respective repos into well-defined modules inside a monolith repo. It is still possible to split responsibilities into their own silos in a unified repo. It just takes more discipline.


You can take a look at this NPM package. This package would allow each Micro Frontend to have its own redux store but allow other Micro Frontends to see and subscribe to state changes of other Micro Frontends.

Github
https://github.com/microsoft/redux-micro-frontend

NPM
https://www.npmjs.com/package/redux-micro-frontend

Article
https://www.devcompost.com/post/state-management-ii-world-of-micro-frontends

Might solve your problem.


Use synthetic events for cross micro frontends communication using eventListeners and CustomEvent like below:

MF-1:

function Cart() {  const [cartItems, addCartItems] = useState([]);  const handleAddToCart = (event) => {    addCartItems((currentItems) => [...currentItems,    event.detail.item]);  };  useEffect(() => {    window.addEventListener('addToCart', handleAddToCart);    return () => {      window.removeEventListener('addToCart', handleAddToCart)    }  }, [handleAddToCart]);  ...}

MF-2:

function itemLookUp() {  const handleSubmit = (item) => {    const customEvent = new CustomEvent('message', { detail: item });    window.dispatchEvent(customEvent)  }  ...}