Home Web Development Learning Redux

Learning Redux

By Daniel Bugl
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Why Redux?
About this book
The book starts with a short introduction to the principles and the ecosystem of Redux, then moves on to show how to implement the basic elements of Redux and put them together. Afterward, you are going to learn how to integrate Redux with other frameworks, such as React and Angular. Along the way, you are going to develop a blog application. To practice developing growing applications with Redux, we are going to start from nothing and keep adding features to our application throughout the book. You are going to learn how to integrate and use Redux DevTools to debug applications, and access external APIs with Redux. You are also going to get acquainted with writing tests for all elements of a Redux application. Furthermore, we are going to cover important concepts in web development, such as routing, user authentication, and communication with a backend server After explaining how to use Redux and how powerful its ecosystem can be, the book teaches you how to make your own abstractions on top of Redux, such as higher-order reducers and middleware. By the end of the book, you are going to be able to develop and maintain Redux applications with ease. In addition to learning about Redux, you are going be familiar with its ecosystem, and learn a lot about JavaScript itself, including best practices and patterns.
Publication date:
August 2017
Publisher
Packt
Pages
374
ISBN
9781786462398

 

Why Redux?

If you have written a large-scale application before, you will know that managing application state can become a pain as the app grows. Application state includes server responses, cached data, and data that has not been persisted to the server yet.

Furthermore, the User Interface (UI) state constantly increases in complexity. For example, nowadays, routing is often implemented on the client so that we do not need to refresh the browser and reload the whole application in order to load a new page. Client-side routing is good for performance, but it means that the client has to deal with even more state (in comparison to using server-side routing).

As you can imagine, conflicts and inconsistencies in these various kinds of state can be hard to deal with. Managing all these states is hard and, if not managed correctly, application state can quickly grow out of control, like an untended garden.

If all of this was not bad enough, new requirements, such as optimistic updates and server-side rendering, become necessary to be able to keep up with the ever increasing performance demands.

State is difficult to deal with because we are mixing two concepts that can be very unpredictable when put together: Asynchronicity and Mutation.

Asynchronicity means that changes can happen anytime, in an asynchronous manner. For example, a user presses a button that causes a server request. We do not know when the server responds and, for performance reasons, we do not want to wait for the response. This is where Asynchronicity comes into play. We act on a response whenever it occurs, but it is unpredictable when this will happen.

Mutation means any change in the application state, such as storing the result from the server response in our application state or navigating to a new page with client-side routing, would change the value of the current route, mutating the application state.

When putting these two concepts together, bad things can happen. For example, the user might enter some new data and save it, while we are still persisting something else to the server, causing an inconsistent state.

This is where Redux comes in. Redux attempts to make state Mutations predictable, without losing the performance advantages of Asynchronicity. It does so by imposing certain restrictions on how updates can happen. These restrictions make applications predictable and easy to test.

As a result of these restrictions, Redux also provides a great developer experience. When debugging, you can time travel between previous application states, and pinpoint the exact time when a bug occurs. You can also use this functionality in production—when users report a bug, the whole application state can be transmitted. This means that you can load the exact state of the application when the bug occurred, making reproduction trivial:

The Redux development experience (all state changes are visible, certain actions can be disabled, and the state will be recalculated)

Furthermore, Redux is very simple and uses plain JavaScript objects and functions. As a result, it can run in various different environments, such as a web client (browser), native applications, and even on the server.

To start out, we will cover the basic elements of a Redux application. Afterwards, we will also cover the restrictions mentioned earlier, resulting in the fundamental principles of Redux. Next, we will focus on how to use Redux with React, a library that shares similar principles and is used to generate user interfaces from the data maintained in Redux. Then, we will teach you how to use Redux with Angular, a framework that is also used to generate user interfaces. Next, we will dive deep into how to solve common problems in web development (such as debugging, user authentication, or interfacing with third-party APIs) with Redux:

How Redux and React play together

Finally, we will discuss how to extend Redux by implementing generic solutions that work with all Redux applications. These generic solutions can be distributed as libraries and there are already many of these out there. For example, to implement undo/redo functionality in any application, you simply use a library, and it will work, regardless of how your application is structured.

In this book, we will develop a blog application with Redux. This application will keep getting extended throughout the chapters and help us practice concepts learned in the book.

In this chapter, we will cover:

  • Defining the state of our application
  • Defining actions
  • Tying the state and actions together
  • Learning about Redux's three fundamental principles
  • Introducing the Redux ecosystem
 

Defining the application state

Before we start implementing a Redux application, we first have to think about the application state. The state of a Redux application is simply a JavaScript value (usually an object).

The application state includes all data needed to render the application and handle user actions. Later, we will use parts of the application state to render HTML templates and make API requests.

You might not know the full application state in the beginning; that's fine. We will make sure that we design our application state in an extendable way. In a Redux application, the state is usually represented as a JavaScript object. Each property of the object describes a substate of the application.

For example, a simple blog application state could consist of an array of posts (which are written by the user and contain some text):

{ 
posts: [
{ user: 'dan', text: 'Hello World!' },
{ user: 'des', text: 'Welcome to the blog' }
]
}

Imagine that we want to add a category string to posts later—we can simply add this property to the objects in the posts array:

{ 
posts: [
{ user: 'dan', category: 'hello', text: 'Hello World!' },
{ user: 'des', category: 'welcome', text: 'Welcome to the blog' }
]
}

Now, let's say we want to implement filtering posts by category; we could extend our state object with a filter property that stores the category as a string:

{ 
posts: [
{ user: 'dan', category: 'hello', text: 'Hello World!' },
{ user: 'des', category: 'welcome', text: 'Welcome to the blog' }
],
filter: 'hello'
}

We can reconstruct the whole application state from this object. Being able to do this is one of the things that makes Redux so awesome.

In a later chapter, we will observe how to add the logic that actually filters posts by making use of the application state.

You might think that the application state will become a very complicated object at some point, and that's true—but in a more advanced project; the state won't be defined in a single file. Application state can be split up and dealt with in multiple files (a separate file for each substate), then combined together.

To keep things simple, let's define our application state as an array of posts for now:

[ 
{ user: 'dan', category: 'hello', text: 'Hello World!' },
{ user: 'des', category: 'welcome', text: 'Welcome to the blog' }
]
 

Defining actions

Now that we have defined the state of our application, we also need a way to change the state. In Redux, we never modify the state directly. To ensure that the application is predictable, only actions can change the state. Redux actions are simply JavaScript objects, with a type property that specifies the name of the action. Let's say we want to create a new post in our blog, we could use an action like this:

{ type: 'CREATE_POST', user: 'dan', text: 'New post' } 

Later on, we could define another action for setting the filter:

{ type: 'SET_FILTER', filter: 'hello' }

These action objects can be passed to Redux, resulting in a new state being calculated from the current state and the action. This process is called dispatching an action.

The way state changes are processed in Redux makes them very explicit, clear, and predictable. If you want to find out how a certain state change happened, just look at the action that was dispatched. Furthermore, you can reproduce state changes by reverting and redispatching actions (also known as time traveling).

 

Tying state and actions together

After defining the application state and actions, we still need a way to apply actions to change the application state. In Redux, the state is updated through special functions called reducers. Reducers contain the state changing logic of our application.

newState = reducer(state, action)

A reducer function takes the current state object and an action object as arguments. The reducer parses the action object, specifically, the action.type. Depending on the action type, the reducer function either returns a new state, or it simply returns the current state (if the action type is not handled in this reducer).

To write a function, we first have to think of the function signature (the head of the function). A reducer function takes the current state and an action argument. For the state argument, we set a default value, which is what the initial state is going to be.

In our example application, the initial state is an empty array of posts, so we can define the reducer function, as follows:

function postsReducer (state = [], action) { 

Now, we will need to parse the action object. The most common way to handle actions in Redux is using a switch statement on action.type. That way, we can have separate cases for all the different action types that the reducer function is going to take care of:

  switch (action.type) {   

In the switch statement, we handle the CREATE_POST action we defined earlier using Array.concat to add the new post object to the state (an array of posts):

    case 'CREATE_POST': 
return state.concat([{ user: action.user, text: action.text }])

For all other action types, we simply return the current state:

    default: 
return state

}
}
Please note that the default branch is very important. If you do not return the current state for unhandled action types, your state will become undefined.
 

Redux' three fundamental principles

As mentioned earlier, Redux is based on certain principles and restrictions. The API of Redux is very small and only consists of a handful of functions. These principles and restrictions are what makes Redux so powerful, and you need to stick to them to be able to reap all the benefits of Redux.

We will now discuss the three fundamental principles of Redux:

  • Single source of truth
  • Read-only state
  • State changes are processed with pure functions

Single source of truth

Redux consists of a single store, which is a JavaScript value containing the entire state of your application. A single source of truth comes with a lot of benefits:

  • In traditional applications, the state is stored in different places across the whole application. With a single source of truth, debugging becomes easy, as you simply have one value to look at.
  • It is easy to create universal apps, as you can serialize the application state on the server and send it to the client without much effort.
  • Generalized functionalities, such as undo/redo, become easy to implement. For example, you can simply drop in a library that turns (a part of) your state into an undoable state.

To access the application state, Redux provides a .getState() function on the store object. You can view the full state, as follows:

console.log(store.getState()) 

The output of the preceding code will be the application state. In our example application, the output would be the post array we defined earlier:

[ 
{ user: 'dan', text: 'Hello World!' },
{ user: 'des', text: 'Welcome to the blog' }
]

The read-only state

In a Redux application, you cannot modify application state directly. The only way to change the state is by dispatching actions:

  • This restriction ensures that state changes are predictable. If no action happens, nothing in the application changes.
  • Because actions are processed one at a time, we do not have to deal with race conditions.
  • Because actions are plain JavaScript objects, they can be easily serialized, logged, stored, and replayed. This makes debugging and testing easy.

A Redux action object (to create a new post) could look like this:

{ type: 'CREATE_POST', user: 'dan', text: 'New post' } 

State changes are processed with pure functions

Given the same input, pure functions always return the same output. Because reducer functions are pure, given the same state and action, they are always going to return the same new state. This makes them predictable.

The following code defines an impure function, because subsequent calls with the same input result in different output:

var i = 0 
function impureCount () {
i += 1
return i
}
console.log(impureCount()) // prints 1
console.log(impureCount()) // prints 2

As you can see, we are accessing a variable outside of the function which is what makes the function impure.

We could make the function pure by specifying i as an argument:

function pureCount (i) { 
return i + 1
}
console.log(pureCount(0)) // prints 1
console.log(pureCount(1)) // prints 2

Pure functions should only work with their input arguments and constants. For reducer functions, being pure means that all nontemporary data should be stored in the state object.

Reducers in Redux are always pure functions. They take the previous state and an action as arguments and return a new state object. The new part is important here. We never modify the passed state directly, because that would make the function impure. We always need to create a new state object based on the old state.

In our reducer function, we used Array.concat to create a new array from the old state array, adding the new post at the end:

function postsReducer (state = [], action) { 
switch (action.type) {

case 'CREATE_POST':
return state.concat([{ user: action.user, text: action.text }])

default:
return state

}
}

You might think that such a reducer function will become very complicated, as it deals with the whole application state. Usually, you start out with a single simple reducer. As your application grows, you can split it up into multiple smaller reducers, each reducer dealing with a specific part of the application state. Because reducers are just JavaScript functions, it is easy to combine them, pass additional data, and even make reusable reducers for common functionality, such as undo/redo or pagination.

 

Introduction to the Redux ecosystem

As a result of Redux' small API and principles that make it very extensible, there is a huge ecosystem surrounding it. You will learn about some libraries throughout this book:

  • react-redux: These are the official React bindings for Redux. They allow you to inject (parts of) the Redux store into your React components. Furthermore, they inject action creators (functions that return action objects), which can automatically dispatch actions to the Redux store. This allows you to communicate in both ways between React and Redux (https://github.com/reactjs/react-redux).
  • ng-redux: This library lets you connect your Angular components with Redux. It works similar to React-Redux (https://github.com/angular-redux/ng-redux).
  • @angular-redux/store: This library helps you to integrate the Redux store with Angular 2+ applications, similar to react-redux. It uses an approach based on RxJS Observables to select and transform data from the Redux store. It allows you to inject this data into your UI or side-effect handlers (https://github.com/angular-redux/store).
  • redux-devtools: This is the official implementation of developer tools for Redux and allows watching state changes, live editing of actions, time traveling, and more. There are many monitor components available, each of them allowing you to debug your application in different ways. For a list of monitors, check out the redux-devtools repository on GitHub (https://github.com/gaearon/redux-devtools).
  • redux-promise: This is middleware for Redux that allows you to dispatch JavaScript promises to the Redux store. These promises will be evaluated and can result in multiple actions, for example, a success and an error action as the result of a server request (https://github.com/acdlite/redux-promise).
  • redux-auth: This library allows you to easily integrate token-based authentication into your Redux application. It supports various ways of authentication, such as OAuth2 and e-mail authentication. It also includes React components for common functionality—for example, registration, login, logout, password reset, updating passwords, and deleting accounts. These components include support for various themes, such as Material UI and React Bootstrap. Overall, this is a very extensive library that should simplify dealing with authentication a lot (https://github.com/lynndylanhurley/redux-auth).
  • react-router-redux: This allows for additional communication between React Router and Redux. You can use React Router without this library, but it is useful to record, persist, and replay user actions using the time traveling. It also helps you keep the routing-related state in sync with your Redux store (https://github.com/reactjs/react-router-redux).
  • redux-UI-router: This library is similar to react-router-redux, but for Angular. It maintains router state for your Angular application via Redux (https://github.com/neilff/redux-ui-router).
  • @angular-redux/router: This is basically the same as redux-UI-Router, but for Angular 2. It maintains router state for your Angular 2 application via Redux (https://github.com/angular-redux/router).
  • redux-undo: This is a higher-order reducer that allows you to make an existing reducer undoable. Basically, it is the easiest way to implement the undo/redo functionality with Redux (https://github.com/omnidan/redux-undo).
  • redux-logger: This is middleware to log Redux actions and state changes in the console (https://github.com/evgenyrodionov/redux-logger).

You can find an official overview of the Redux ecosystem on the Redux website: http://redux.js.org/docs/introduction/Ecosystem.html.

There is also a community-maintained repository called Awesome Redux, which contains resources, libraries, boilerplates, and examples related to Redux: https://github.com/xgrommx/awesome-redux.

 

Summary

In this chapter, we covered the principles that make Redux special, and why it should be used in a project. We started out with the motivation behind Redux (complexity of state management), then briefly covered how Redux works in practice. We also discussed how certain restrictions allow us to write maintainable, consistent, and easy-to-test applications. Wrapping up, we took a look at the very extensive Redux ecosystem.

In the next chapter, we will discuss how to set up a Redux project. Afterwards, we will implement the basic elements of Redux and see how they work together in practice.

About the Author
  • Daniel Bugl

    Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.

    Browse publications by this author
Latest Reviews (2 reviews total)
Todavía estoy en la fase inicial de lectura, pero impresiona tener el potencial para adquirir fluidez en el manejo de una herramienta central para trabajar en el marco de React.js
Muy bien escrito y muy buena data. Aprendo cosas nuevas cada vez que leo el libro
Learning Redux
Unlock this book and the full library FREE for 7 days
Start now