Our dev team recently became responsible for building micro front-ends using React for e-commerce sites. After building our second site, we noticed there was a lot of duplication among our redux actions and how they handle common backend interactions. For example, a user adding an item to a cart or logging in is the exact same across applications.

Inevitably, we discovered a bug affecting an action with carts and ended up applying a fix to reducers on both sites… while it’s trivial to copy and paste a fix across two sites, we could only imagine having this problem span dozens. What about refactors? This was not sustainable. There are a lot of articles and opinions about creating shared component libraries but what about shared state management libraries?

We knew we needed to create an NPM package that our current and future sites could leverage but there was the question of how to reconcile app-specific logic we want redux to handle. For example, what if site A needs a reducer to handle some specific logic that is scoped only to that site? One approach is to use 2 stores in a React app. This method quickly proved error-prone and would potentially place a lot of cognitive load on developers.

The problem with using 2 stores is the additional boilerplate code you need to use for useDispatch or useSelector to work. In the example below, we are passing context to our redux hooks to identify which store to access. Having two stores means two sets of dispatch useSelector etc…

#redux #javascript #react

Creating a Shared State Library for Micro-Frontends using Redux
25.45 GEEK