Forward Advance Learning

Introducing Plain Ol' Redux

In the last section, we saw how we could build a Flux architecture using simple ES6. Luckily, we don't need to do this, because Flux already handles the store for us.

Redux is an immutable data store. It's typically paired with React to make a Flux architecture, but it can be used alone. It maintains a state, which represents the current state of your app. State is typically an object, but could be something simpler like an array, or even a single number.

Any application can be represented as a set of data. The UI that you hang off that data is up to you, and possibly subject to change, but the data itself is what the user wants to interact with.

Redux is the magical, immutable database for your app.

(state, action) => state

Redux can be described as a system that accepts a current state, and an action, and returns a new state. We call the function that does this a reducer.

We pass the reducer to Redux.createStore, to make our store. Anytime we dispatch to the store, the reducer has the opportunity to change the state of the store.

Things to know about Redux

Here's a simple Redux handler (written in ES6) that handles a counter. In this case the state is an object containing a value which is a number.

const reducer = (state=defaultState, action) => {
switch (action.type) {
case "INC":
return {...state, value: state.value + 1}
case "DEC":
return {...state, value: state.value - 1}
return state

To make use of this, we pass it into a new store:

var store = Redux.createStore(reducer)

We can then subscribe to that store with a callback function:

store.subscribe(() => console.log(store.getState()));

Each time the state changes, the callback function will run. Inside this callback function, we typically re-render our app.

When we want to trigger an action, we dispatch an action to the store:


Here's that in action. I've added a bit of logging and a timeout for effect:

See the Pen Redux Demo by Nicholas Johnson (@superluminary) on CodePen.

Add a plus10 action that adds ten to the state, and trigger it at random intervals


State is immutable. This means that every time we change state, we create a brand-new state object and return that.

We don't necessarily need to duplicate everything that is in state, though we will want to duplicate everything that has changed. State itself will be a new object each time we call store.dispatch with a valid action.

This will help us optimise our compile. If nothing has changed, React knows it doesn't need to re-render.