Skip to main content

Redux

Redux is an open-source JavaScript library for managing application state. It is most commonly used with libraries such as React or Angular for building stateful user interfaces. Without a state management library, such as Redux, large applications may suffer from excessive prop management, making building and maintaining applications difficult. Redux also helps to create applications which behave consistently, run in different environments (client, server, and native), and are easy to test. There are a few alternatives to Redux (MobX, Flux, React Hooks API) but, at the time of writing, Redux has a large following and a lot of community support. Developer tools are available for both Google Chrome and Mozilla Firefox.

How it works

Redux is built of 3 main parts: actions, reducers, and the store. Actions are payloads of information which send data from the application to the Redux state store. Reducers specify how the application's state changes in response to actions sent to the store. Reducers are often used to separate out parts of the state store into meaningful chunks. Finally, the store is the object which holds the state of the application.

Recommendations

The Container Pattern

A popular approach for React with Redux is the 'container pattern'. A container component is responsible for retrieving data and dispatching actions that make changes to application state. These actions and data are passed into a presentation component and simply displays it as a normal prop and doesn't care how or where it came from. This allows for separation of concerns. The container component is worried about how things work, while the presentation component worries about how things look; this separation opens up the possibility of component re-use.

Async Actions

Rather than writing custom middleware to execute async actions, include a single middleware, such as redux-thunk, that takes actions, which are functions (thunks), and executes them. Also, it encourages the use of action creators which return a function instead of an action. A thunk can be used to delay the dispatch of an action, or to dispatch once a certain condition has been met. This provides a consistent pattern for queuing actions-that-do-async-things-that-create-actions without having to worry about middleware nesting order, etc. Auditing a chain of actions also becomes easier. Additionally, thunk functions are typically easier to test.

Caveats

It may be tempting to put all application state into the Redux store, but leaving non-critical UI state inside components may suffice and may keep the amount of boilerplate Redux code to a minimum. Consider whether or not the rest of the application will need to access data in the Redux store. Furthermore, consider whether any component libraries, such as Storybook, readily support Redux.