Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Redux
Learning Redux

Learning Redux: Write maintainable, consistent, and easy-to-test web applications

By Daniel Bugl
$43.99 $29.99
Book Aug 2017 374 pages 1st Edition
eBook
$43.99 $29.99
Print
$54.99
Subscription
$15.99 Monthly
eBook
$43.99 $29.99
Print
$54.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Aug 31, 2017
Length 374 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786462398
Category :
Table of content icon View table of contents Preview book icon Preview Book

Learning Redux

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Write applications that behave consistently, run in different environments (client, server and native), and are easy to test
  • Take your web apps to the next level by combining the power of Redux with other frameworks such as React and Angular
  • Uncover the best practices and hidden features of Redux to build applications that are powerful, consistent, and maintainable

Description

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.

What you will learn

• Understand why and how Redux works • Implement the basic elements of Redux • Use Redux in combination with React/Angular to develop a web application • Debug a Redux application • Interface with external APIs with Redux • Implement user authentication with Redux • Write tests for all elements of a Redux application • Implement simple and more advanced routing with Redux • Learn about server-side rendering with Redux and React • Create higher-order reducers for Redux • Extend the Redux store via middleware

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Aug 31, 2017
Length 374 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781786462398
Category :

Table of Contents

13 Chapters
Preface Chevron down icon Chevron up icon
1. Why Redux? Chevron down icon Chevron up icon
2. Implementing the Elements of Redux Chevron down icon Chevron up icon
3. Combining Redux with React Chevron down icon Chevron up icon
4. Combining Redux with Angular Chevron down icon Chevron up icon
5. Debugging a Redux Application Chevron down icon Chevron up icon
6. Interfacing with APIs Chevron down icon Chevron up icon
7. User Authentication Chevron down icon Chevron up icon
8. Testing Chevron down icon Chevron up icon
9. Routing Chevron down icon Chevron up icon
10. Rendering on the Server Chevron down icon Chevron up icon
11. Solving Generic Problems with Higher-Order Functions Chevron down icon Chevron up icon
12. Extending the Redux Store via Middleware Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.