Debunking Redux Black Legend
Redux is simple: A Global state manager. It was designed for React because it was a huge pain to “drill props” on 18 layers of components.
Despite this simplicity, coders misuse it by moving the local state to the global state. And this is why we found people moving:
- All API calls: If the data is not shared, it is not a global state.
- Modal contents: use React Portals.
- Router: removing
react-router-redux
is a huge pain.
- Removing local state: Some coders are willing to create a reducer in the global store, actions types, and selectors only to avoid drilling props 2. If you have to drill props more than 2 levels consider using React context.
When you start adding almost everything to the global store is a question of time before the sh** hit the fan, and when it happens nobody will blame themselves, they will blame the good old Redux.
These are old news, nowadays we have a Black Legend about this library, I am going to point out why Redux is very often the best option:
- It is popular: This will help to hire coders and they will be closer to master Redux approaches. This is valuable for the company but also for the coder, a new skill in his resume. In-house solutions don’t have this value for any of them.
- It is almost native: The people developing Redux are the same people developing React.
- It is solid: Years of dealing with React (mainly) make this library pass the test of time, their engineers has dealt with problems related more than your company would be because it is very likely you develop apps and not libraries for React.
- Third-party extensions: Debugging, Testing, Server Side Rendering, middlewares…
- It is easy: moreover after Redux-Toolkit
Some advice for implementing Redux
- Stick to the shared state: With things such as Firebase Firestore you might not need to share a lot of data, updates happen in real-time so all components are synced without a global store.
- Use Redux Toolkit: It removes a lot of complexity noise in the implementation. It comes with
Slices
that is a nice way of modularizing your store. Also, you can do async functions without needing any other libraries. Plenty of hooks likeuseSelector
that will make your life easier. If you can’t update redux use Ducks pattern - Selectors, selectors, selectors: Store data from API as is, any transformation use a selector. Nest the selectors and if you are in the need of more performance use Reselect library to memorize. You could cache these selector later and boost performance.
- Don’t combine data from multiple sources in the same store slice. A huge Slice is a huge problem, a small slice is no problem at all. You can’t be wrong with a small slice.
Summary
Redux suffers the same problem CSS has: If you don’t master it you will most likely hate it.