Redux is React's version of global variables?
Portals through the component hierarchy
I’ve been digging into a React/Redux project at work recently. The React parts were easy to pickup, but the Redux part was a bit mysterious at first.
- What is this folder of exported strings called “actionTypes”?
- What are all these “reducers” and why do they not seem to do anything?
- What is mapStateToProps and mapDispatchToProps doing at the bottom of all these components?
Two things helped me understand:
- Redux is a way to share “global” values across components
- Much of the apparent complexity of Redux is actually just convenience methods and helpers.
Redux has great documentation, but ultimately I had to build a small example to understand what the point of the whole thing was. The example contains a counter and a selector for choosing your preferred locale (US, Germany, or Egypt).
With plain React, state is usually passed via component props; so in the simplest design, the locale selector would be the parent of the counter. This is not a great solution as it makes the locale selector less composable (it is tied to a counter). A better design is to lift the state (the current locale) into a higher, parent component. The parent can then pass the state to both locale selector and counter components. This is powerful, but there are drawbacks:
- tendency towards having a single ‘God’ component that holds the app’s entire state
- changing shared state requires passing handler functions adding indirection and increasing props (child components call these functions to trigger changes in an ancestor)
- in a large app, sharing state between components that are deeply nested in two different hierarchies can be challenging/awkward
Redux provides an alternative way of sharing state between components. Instead of storing state in a common ancestor and sharing via props, state is stored in a global store. Components subscribe to the store (alerting them of changes) and dispatch actions to change the store. It’s like having a global object that all components can read and write to, but safer and more regulated. Since state is no longer restricted to being passed down from parent to child, Redux allows for “flatter” component hierarchies.
That said, you might not need it.