Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Redux

You're reading from   Learning Redux Write maintainable, consistent, and easy-to-test web applications

Arrow left icon
Product type Paperback
Published in Aug 2017
Publisher Packt
ISBN-13 9781786462398
Length 374 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Daniel Bugl Daniel Bugl
Author Profile Icon Daniel Bugl
Daniel Bugl
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

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

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime