Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.
Redux is available as a package on NPM for use with a module bundler or in a Node application:
npm install –save redux
Core Concepts
Imagine your app’s state is described as a plain object. For example, the state of a todo app might look like this:
{
todos: [{
text: ‘Eat food’,
completed: true
}, {
text: ‘Exercise’,
completed: false
}],
visibilityFilter: ‘SHOW_COMPLETED’
}
This object is like a “model” except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs.
To change something in the state, you need to dispatch an action. An action is a plain JavaScript object (notice how we don’t introduce any magic?) that describes what happened. Here are a few example actions:
{ type: ‘ADD_TODO’, text: ‘Go to swimming pool’ }
{ type: ‘TOGGLE_TODO’, index: 1 }
{ type: ‘SET_VISIBILITY_FILTER’, filter: ‘SHOW_ALL’ }
Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magical about it—it’s just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:
function visibilityFilter(state = ‘SHOW_ALL’, action) {
if (action.type === ‘SET_VISIBILITY_FILTER’) {
return action.filter
} else {
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case ‘ADD_TODO’:
return state.concat([{ text: action.text, completed: false }])
case ‘TOGGLE_TODO’:
return state.map((todo, index) =>
action.index === index
? { text: todo.text, completed: !todo.completed }
: todo
)
default:
return state
}
}
And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:
function todoApp(state = {}, action) {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
}
}
This is basically the whole idea of Redux. Note that we haven’t used any Redux APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to action objects, and 90% of the code you write is just plain JavaScript, with no use of Redux itself, its APIs, or any magic.
Basic Example
The whole state of your app is stored in an object tree inside a single store. The only way to change the state tree is to emit an action, an object describing what happened. To specify how the actions transform the state tree, you write pure reducers.
import { createStore } from ‘redux’
/**
* This is a reducer, a pure function with (state, action) => state signature. It describes how an *action transforms the state into the next state.
* The shape of the state is up to you: it can be a primitive, an array, an object,
* or even an Immutable.js data structure. The only important part is that you should
* not mutate the state object, but return a new object if the state changes.
*
* In this example, we use a `switch` statement and strings, but you can use a helper that
* follows a different convention (such as function maps) if it makes sense for your
* project.
*/
function counter(state = 0, action) {
switch (action.type) {
case ‘INCREMENT’:
return state + 1
case ‘DECREMENT’:
return state – 1
default:
return state
}
}
// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)
// You can use subscribe() to update the UI in response to state changes.
// Normally you’d use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.
store.subscribe(() => console.log(store.getState()))
// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: ‘INCREMENT’ })
// 1
store.dispatch({ type: ‘INCREMENT’ })
// 2
store.dispatch({ type: ‘DECREMENT’ })
// 1
Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions. Then you write a special function called a reducer to decide how every action transforms the entire application’s state.
In a typical Redux app, there is just a single store with a single root reducing function. As your app grows, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. This is exactly like how there is just one root component in a React app, but it is composed out of many small components.
This architecture might seem like an overkill for a counter app, but the beauty of this pattern is how well it scales to large and complex apps. It also enables very powerful developer tools, because it is possible to trace every mutation to the action that caused it. You can record user sessions and reproduce them just by replaying every action.
Installing React Redux
React bindings are not included in Redux by default. You need to install them explicitly:
npm install –save react-redux
Presentational and Container Components
React bindings for Redux separate presentational components from container components. This approach can make your app easier to understand and allow you to more easily reuse components. Here’s a summary of the differences between presentational and container components
Presentational Components | Container Components | |
Purpose | How things look (markup, styles) | How things work (data fetching, state updates) |
Aware of Redux | No | Yes |
To read data | Read data from props | Subscribe to Redux state |
To change data | Invoke callbacks from props | Dispatch Redux actions |
Are written | By hand | Usually generated by React Redux |