Redux is React's version of global variables?

Portals through the component hierarchy

October 20, 2019

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.

Two things helped me understand:

  1. Redux is a way to share “global” values across components
  2. 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:

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.