You are on page 1of 35

Redux: The Single Immutable State Tree

The first principle of Redux is whether your app is a really simple one like this counter example, or a
complex application with a lot of UI, and change of state, you are going to represent the whole state of
your application as a single JavaScript object.

All mutations, and changes the state in Redux are explicit. It is possible to keep track of all of them. In
this case, I am logging every state change in the application in the console. You can see that, in the
counter example, there isn't really much state to keep track of so it can be represented by a JavaScript
number.

Here is a different example, a list of independent counters that I can add and remove. In this case, a
single number is not enough to represent the state of the application, so we use an array of JavaScript
numbers. In a more complex application, there is more state to keep track of.

This is a typical to-do app, where I can add to-dos, I can cross them as completed ones, and I can change
their current filter. Looking back at the history of the state changes, we can see that the initial state of
the app was a JavaScript object, containing an array under the to-do string, and a string seen show all,
under visible, the filter.

When I added the first to-do, it was added to the to-dos array, inside our state object. The to-do itself, is
described by a plain child script object, saying it was not completed, and the text was saved. Every
further change that the app, whether when I was crossing out the to-dos, or when I changed the
visibility filter, resulted in this change to this state object, described in our whole application.

Now you know the first principle of Redux, which is that, everything that changes in your application,
including the data and the UI state, is contained in a single object, we call the state or the state tree.

Redux: Describing State Changes with Actions

The second principle of Redux is that the state tree is read only. You cannot modify or write to it.
Instead, anytime you want to change the state, you need to dispatch an action.

An action is a plain JavaScript object describing the change. Just like the state is the minimal
representation of the data in your app, the action is the minimal representation of the change to that
data.

The structure of the action object is up to you. The only requirement is that it has a tie property, which
is not undefined. We suggest using strings, because they are serializable.

In different apps, you're going to have different types of actions. For example, in a counter app we only
have increment and decrement actions. We don't pass any additional information, because this is all
that is needed to describe these changes.

1
But say, for a counter release example, we have more actions. We have add counter action, we have a
remove counter action, and anytime I change the individual counter, you can see that the increment and
the decrement actions now have index. Because we need to describe which particular counter was
changed.

This approach scales well to medium and complex applications. Anytime I add a todo, the components
don't really know how exactly it's been added. All they know is that they need to dispatch an action with
a type, add todo, and the text of the todo and a sequential ID.

If I toggle a todo, again, the components don't know how it happens. All they need to do is to dispatch
an action with a type, toggle todo and pass in the ID of the todo I want to toggle.

The same is true for the visibility filter. Anytime I click on this control to change the currently visible
todos, what really happens is this component dispatches an action with a type, set visibility filter, and
pass in the desired filter string, filter filled.

But these are all plain objects, describing what happens in a wrap.

Now you know the second principle of Redux -- the state is read only. The only way to change the state
tree is by dispatching an action. An action is a plain JavaScript object, describing in the minimal way
what changed in the application. Whether it is initiated by a network request or by user interaction, any
data that gets into the Redux application gets there by actions.

Redux: Pure and Impure Functions

Before we proceed any further, it's important that you understand the difference between the pure and
impure functions. The pure functions are the functions whose returned value depends solely on the
values of their arguments.

Pure functions do not have any observable side effects, such as network or database calls. The pure
functions just calculate the new value. You can be confident that if you call the pure function with the
same set of arguments, you're going to get the same returned value. They are predictable.

Also, pure functions do not modify the values passed to them. For example, squareAll function that
accepts an array does not overwrite the items inside this array. Instead, it returns a new array by using
items map.

On the opposite, impure functions may call the database or the network, they may have side effects,
they may operate on the DOM, and they may override the values that you pass to them. This is going to
be an important distinction because some of the functions that you're going to write in Redux have to
be pure, and you need to be mindful of that.

Redux: The Reducer Function

2
You might have heard that the UI or the view layer is most predictable when it is described as a pure
function of the application state. This approach was pioneered by React but is now being picked up by
other frameworks, such as Ember and Angular.

Redux complements this approach with another idea, that the state mutations in your app need to be
described as a pure function that takes the previous state and the action being dispatched and returns
the next state of your application.

Inside any Redux application, there is one particular function that takes the state of the whole
application and the action being dispatched and returns the next state of the whole application. It is
important that it does not modify the state given to it. It has to be pure, so it has to return a new object.

Even in large applications, there is still just a single function that manages how the next state is
calculated based on the previous state of the whole application and the action being dispatched. It does
not have to be slow.

For example, if I change the visibility filter, I have to create a new object for the whole state, but I can
keep the reference to the previous version of the todos rate, because it has not changed when I changed
the visibility filter. This is what makes Redux fast.

Now you know the third and the last principle of Redux. To describe state mutations, you have to write a
function that takes the previous state of the app, the action being dispatched, and returns the next state
of the app. This function has to be pure. This function is called the "Reducer."

Redux: Writing a Counter Reducer with Tests

The first function we're going to write is the reducer for the counter example. Reducer accepts straight
and action as arguments and returns the next trait. Before jumping into the implementation, we're
going to make certain assertions using Michael Jackson's Expect library. We're going to assert that when
the straight of the counter is zero and you pass an increment action it should return one. Similarly it
should return two when this straight is one and you increment.

We're going to add a couple of tests that test how decrement works, which is that it decrements from
two to one and from one to zero and we're going to add a log to tell if our tests are successful.

If you ran this test, they're actually going to fail because we haven't even begun to implement our
reducer. We're going to start by checking the action type and if the action type is increment we're going
to return straight plus one, but if it is decrement we're going to return straight minus one.

If you run the tests we will find that this is enough to get them to pass. However, there are still some
flaws in our current implementation of the counter reducer. For example, I think that if we dispatch an
action that it does not understand, it should return the current straight of the application.

However, if we check for that we will see that this test fails, because we currently don't handle unknown
actions. I'm going to add an else clause that returns the current straight. The tests pass now.

3
Another issue is that while the reducer is normally in control of the application straight, currently it does
not specify the initial straight. In the case of counter example that would be zero. The convention we
use in Redux is that if the reducer receives undefined as the straight argument, it must return what it
considers to be the initial straight of the application. In this case it will be zero.

Now come a few cosmetic tweaks. I'll replace this bunch of tweaks with a switch statement and I'm
going to replace this condition with ES6 default argument, which looks better. I'm also going to replace
the function declaration with an arrow function, which has clearer semantics in ES6.

Redux: Store Methods: getState(), dispatch(), and subscribe()

I added Redux to our application as a script act from CDNJS. This is the UMG build, so it exports a single
global variable called Redux, with a capital R. In real applications, I suggest you to use NPM instead and a
module bundler like webpack or Browserify, but the UMG build will suffice for our example.

I'm going to need just a single function from Redux called create store. I'm using ES6 destruction syntax
here. It's equivalent to writing, "var creates store equals Redux.creates chore" or, if you use NPM and
something like Babel to transpile your ES6, you can write, "import creates store," notice the parenthesis,
"from Redux."

This store binds together the three principles of Redux. It holds the current application's state object. It
lets you dispatch actions. When you create it, you need to specify the reducer that tells how state is
updated with actions.

In this example, we're calling creates store with counter as the reducer that manages the state updates.
This store has three important methods.

The first method of this store is called get state. It retrieves the current state of the Redux store. If we
were on this, we're going to see zero because this is the initial state of our application.

The second and the most commonly used chore method is called dispatch. It lets you dispatch actions to
change the state of your application. If we log this chore state after dispatch, we're going to see that it
has changed.

Of course, always log into the console gets boring, so we're actually going to render something to the
body with the help of the third Redux store method, called subscribe. It lets you register a callback that
the Redux store will call any time an action has been dispatched, so that you can update the UI of your
application. It will reflect the current application state.

I'm being very naive now. I'm not using React or anything. I'm just rendering the counter into the
document body. Any time the body is clicked, I'm going to dispatch an action to increment this counter.

If you pay close attention, you will notice that the initial state, the zero, was not rendered. This is
because I'm rendering inside the subscribe callback, but it doesn't actually fire the very first time.

4
So I extract this logic into render method. I subscribe the render method to this store. I also call it once
to render the initial state. Now it renders the zero, and the click increments the counter. This is our first
working Redux application.

Redux: Implementing Store from Scratch

In the previous video we looked at how to implement a simple counterexample using the Create/Store
function provided by Redux and the store object it returns that provides the get straight method to get
the current application state, the dispatch method, to change the current application state by
dispatching an action, and the subscribe method to subscribe to the changes and re-render our
application with the current state of the app.

If you're like me you prefer to understand the tools that you're using. In this tutorial we're going to re-
implement the Create/Store function provided by Redux from scratch. The first and the only form of
what we know so far argument to the Create/Store function is the reducer function provided by the
application.

We know that the store holds the current state. We keep it in a variable, and the get straight function is
going to return the current value of that variable. This function, combined with the Dispatch function
and a Subscribe function on a single object is what we call the Redux store.

Because the Subscribe function can be called many times, we need to keep track of all the changed
listeners. Any time it is cold we want to push the newly listener into the array. Dispassion in action is the
only way to change the internal state.

In order to calculate the new state we call the reducer with the current state and the action being
dispatched. After the state was updated, we need to notify every changed listener, by calling it.

There is an important missing piece here. We haven't provided a way to unsubscribe a listener. Instead
of adding a dedicated Unsubscribe method, we'll just return a function from the Subscribe method that
removes this listener from the listeners' array.

Finally, by the time the store is returned we wanted to have the initial state populated. We're going to
dispatch a dummy action just to get the reducer to return the initial value.

This implementation of the Redux store apart from a few minor details in that case is, is the
Create/Store was shipped with Redux.

Redux: React Counter Example

In the simplest counter example, I update the document body manually any time this tool state changes.
But, of course, this approach does not scale to complex applications. Instead of manually updating the
DOM, I'm going to use React.

5
I'm adding to script the [inaudible 00:18] corresponding to React and react-dom packages and a root dev
to render to. Now I can call the ReactDOM.render with my root component. The render function is
called any time this store state changes, so I can safely pass the current state of this store as a prop to
my root component.

Since this state is held inside the Redux store, the counter component can be a simple function, which is
a supported way of declaring components since React 14.

I want to add, decrement, and increment buttons to the component, but I don't want to hard-code the
Redux dependency into the component. So I just add on increment and on decrement props as
callbacks. In my render method, I pass the callbacks that call store.dispatch with appropriate actions.
Now the application state is updated when I click the buttons.

Let's recap how this application works. The counter component is what I call a dump component. It does
not contain any business logic. It only specifies how the current application state transforms into
renderable output and how the callbacks, passed via props, are bound to the event handlers.

When we render a counter, we specify that its value should be taken from the Redux store current state.
When the user presses "increment" or "decrement," we dispatch corresponding action to the Redux
store. Our reducer specifies how the next state is calculated based on the current state and the action
being dispatched.

Finally, we subscribe to the Redux store, so our render function runs anytime the state changes, so the
counter gets the current state.

Redux: Avoiding Array Mutations with concat(), slice(), and ...spread

In this lesson, I use Expect Library to make test assertions, and deepFreeze to make sure that my code is
free of mutations.

Let's say that I want to implement a count release application. I would need to write a few functions that
operate on its [?] trait, and its trait is an array of JavaScript numbers representing the individual
counters.

The first function I want to write is called Add Counter, and all it should do is to append a zero at the end
of the past array.

At first, I use the array push method to add a new item at the end of the array, and it works. However,
we need to learn to avoid mutations in Redux, and I'm enforcing this by calling deepFreeze on the
original array.

Now my attempt to push does not work. It cannot add a new property to a frozen object. Instead of
push, I'm going to use the concat method, which does not modify the original array.

Now the tests pass without mutations, and I can also use the new ES6 erase spread operator to write
the same code in a more concise way.

6
My next function is called Remove Counter, and it accepts two arguments, an array of numbers, and the
index of the number to skip from the array.

If I've got three numbers and I'm passing one as the second argument, I expect to receive an array with
two numbers with the second item skipped in the result array.

Usually, to delete an item from the array, I would use the splice method. However, splice is a mutation
method, so you can't use it in Redux.

I'm going to deepFreeze the array object, and now I need to figure out a different way to remove an
item from the array without mutating it.

I'm using a method called slice here, and it doesn't have anything to do with splice. It is not mutating,
and it gives me a part of the array from some beginning to some end index.

What I'm doing is that I'm taking the parts before the index I want to skip and after the index I want to
skip, and I concatenate them to get a new array.

Finally, instead of writing it as a method chain with concat calls, I can use the ES6 erase spread operator
to write it more concisely.

Now that we implemented adding and removing counters, let's implement increment in the counter.
The increment counter function takes your arguments, the array and the index of the counter that
should be incremented, so the return value has the same count of items, but one of them is
incremented.

Directly setting the array value at index works, but this is a mutation. If we add a deepFreeze call, it's not
going to work anymore, so how do we replace a single value in the array without mutating it?

It turns out that the answer is really similar to how we remove an item. We want to take the slice before
the index, concat it with a single item array with a new value, and then concat it with the rest of the
original array.

Finally, with the ES6 spread operator, we can spread over the left part of the array, specify the new
item, and then spread over the right part of the original array, and this looks much nicer.

In this lesson, you learned how to use the concat method or the spread operator, and the slice method
to add, remove, and change items in arrays without mutating them, and how to protect yourself with
deepFreeze from mutation in your tests.

Redux: Avoiding Object Mutations with Object.assign() and ...spread

Like in previous example, I use expect and deep freeze libraries from NPM to make my test assertions.
This time, I'm testing a function called toggle to-do that takes our to-do object and flips its completed
field. If completed was false, it should be true in the return value. If it was true, it should be false.

7
Just like in the previous lesson, I'm going to start by writing a mutated version that passes the current
test. A mutated version just flips the completed field, reassigns it on the past object.

While it works, we know that mutations are not allowed in Redux. So to enforce this, I'm calling deep
freeze on my to-do object. I'm not allowed to change its completed field anymore.

One way out of this would be to create the new object with every field copied from the original object
except the completed field, which would be flipped. However, if we later add new properties to the new
object, we might forget to update this piece of code to include them.

This is why I suggest you to use object assign method, which is new to ES6. It lets you assign properties
of several objects onto the target object.Note how the object assign argument order corresponds to
that of the JavaScript assignment operator.

The left argument is the one whose properties are going to be assigned, so it's going to be mutated. This
is why we're passing an empty object as the first argument, so we don't mutate any existing data. Every
further argument to object assign will be considered one of the source objects whose properties will be
copied to the target object.

It is important that if several sources specify different values for the same property, the last one wins.
This is what we use to override the completed field despite what the original to-do object says.

Finally, you need to remember that object assign is a new method in ES6, so it is not natively available in
all the browsers. You should use a polyfill, either the one that ships with Babel or a standalone object
assign polyfill, to use it without risking crashing your website.

Another option that doesn't require a polyfill is to use the new object spread operator, which is not part
of ES6. However, it is proposed for ES7. It is fairly popular, and it is enabled in Babel if you use the stage
two preset.

Redux: Writing a Todo List Reducer (Adding a Todo)

Just like in the previous two lessons, I'm using expect library to make test assertions and deep freeze
library to prevent accidental mutations in my code. In this lesson, I will create the reducer for a to-do list
application whose state is described an array of to-dos.

Just to remind you what a reducer is, it's a pure function you write to implement the update logic of
your application -- that is, how the next state is calculated given the current state and the action being
dispatched.

Before writing a reducer, I want to have a way of knowing whether its code is correct, so I'm starting by
writing a test for it. I'm declaring two variables, the state before, which is an empty array, and the action
being dispatched, which is an action describing user adding any to-do with some ID and a text.

8
I am also declaring the state I expect to get after calling the reducer. Like state before, it is an array, but
this time, it has a single element representing the to-do that was just added. So it has the same ID and
the text as the action object. It also has an additional field called, "completed," that I want to be
initialized to be false.

We want to make sure that the reducer is a pure function, so I'm calling deep freeze both on the state
and the action. Finally, I am ready to use the expect library to verify that if I call the to-do reducer with
the state before and the action object, I'm going to get the result that is deeply equal to the state after I
just declared.

This concludes my first test. Now I can call it just like a regular JavaScript function. If it doesn't throw in
the expect call, I'm going to see a message saying that the tests have passed.

Of course, it fails because the reducer is not implemented yet. It's an empty function. So it returns
undefined instead of the array with a single item that I expect in the test.

To fix this, I would need my reducer to take a look at the action type property, which is a string. When it
matches the at to-do string, which I specify as the action type in my test, to satisfy the test I need to
return a new array which includes all items from the original array but also a new to-do item that has its
ID and text copied from the action object and a completed field set to false.

Finally, I add a default case to my switch statement because averages has to return the current state for
any unknown action.

Now the test runs successfully. Let's recap the data flow in this example to see why.

First, I create the state array, which is an empty array, and the action object inside my test function. I'm
passing them as arguments to my reducer function, called, "to-dos." The to-dos reducer accepts the
state and the action as arguments and takes a look at the action type.

In this case, the action type is a string saying, "at to-do," so it matches the switch case inside the
reducer. The reducer returns a new array which contains the items from the old array and the new item
representing the added to-do.

However, the state we passed from the test was actually an empty array, so, at the end, we're going to
get an array with a single item, which is the new to-do.

Finally, we compare the return value to an array with a single to-do item to make sure that the reducer
works as intended. The equality check passes. This makes the test successful.

Redux: Writing a Todo List Reducer (Toggling a Todo)

In this lesson, we will continue creating the reducer for to-do list application. The only action that this
reducer currently handles is called At-To-Do. We also created a test that makes sure that when the
reducer is called with an empty array as a state and the at-to-do action, it returns an array with a single
to do element.

9
In this lesson, we will follow the same approach to implement another action called Toggle To-Do. We're
going to start with a test again. This time, we're testing a different action and we have a different initial
state. The state before calling the reducer now includes two different to-dos with ID zero and one.
Notice how both of them have their completed fields set to false.

Next, I declare the action. The action is an object with the type property which is a toggle to-do string
and the ID of the to-do that I want to be toggled. I declare the state that I expect to receive after calling
the reducer. It's pretty much the same as before calling the reducer. However, I expect the to-do with
the ID specified in the action or one in this case. The change is completed field.

The reducer must be a pure function. As a matter of precaution, I called reprise on the state and the
action. Finally, just like in the previous lesson, I'm asserting that the result of calling my reducer with the
state before and the action is going to be deeply equal to the state after.

My test is a function, so I need to call it at the end of the file. If I run it, it fails because I have not
implemented handling this action yet.

I'm adding a new switch case to my reducer. I remember that I shouldn't change the original array, so
I'm using the array map method to produce a new array.

The function I pass as an argument will be called for every to-do. If it's not a to-do I'm looking for, I don't
want to change it. I just return it as is. However, if the to-do is the one we want to toggle, I'm going to
return a new object that has all the properties of the original to-do object thanks to the object's pred
operator, but also an inverted value of the completed field.

Now both of our tests run successfully. We have an implementation of the reducer that can add and
toggle to-dos.

Redux: Reducer Composition with Arrays

In the previous lesson we created a reducer that can handle two actions, adding a new to-do, and
toggling an existing to-do. Right now, the code to update the to-do item or to create a new one is placed
right inside of the to-dos reducer.

This function is hard to understand because it makes us two different concerns, how the to-do's array is
updated, and how individual to-dos are updated. This is not a problem unique to Redux. Any time a
function does too many things, you want to extract other functions from it, and call them so that every
function only addresses a single concern.

In this case, I decided that creating and updating a to-do in response to an action is a separate
operation, and needs to be handled by a separate function called to-do. As a matter of convention, I
decided that it should also accept two arguments, the current trait and the action being dispatched, and
it should return the next trait.

10
But in this case, this trait refers to the individual to-do, and not to the least of to-dos. Finally, there is no
magic in Redux to make it work. We extracted the to-do reducer from the to-dos reducer, so now we
need to call it for every to-do, and assemble the results into an array.

While this is not required in this particular example, I suggest that you always have the default case
where you return the current trait to avoid all [inaudible 1:36] in the future. The part described in this
lesson is pervasive in Redux's development, and is called reducer composition.

Different reducers specify how different parts of the trait tree are updated in response to actions.
Reducers are also normal JavaScript functions, so they can call other reducers to delegate and abstract a
way of handling of updates of some parts of this tree they manage.

This pattern can be applied many times, and while there is still a single top level reducer managing the
state of your app, you will find it convenient to express it as many reducers call on each other, each
contribution to a part of the applications trait tree.

Redux: Reducer Composition with Objects

In the previous lesson, we established the pattern of reducer composition where one reducer can be
called by another reducer to update items inside an array.

If we create a store with this reducer and log its state, we will find that the initial state of it is an empty
array of to dos. If we dispatch an at-to-do action, we will find that the corresponding to do has been
added to the state array.

If we dispatch another at-to-do action, the corresponding to do will also be added at the end of the
array and dispatch in a toggle to do action with ID zero will flag the completed field of the to do with ID
zero.

Representing the whole state of the application as an array of to dos works for a simple example, but
what if we want to store more information? For example, we may want to let the user choose which to
dos are currently visible with the visibility filter such as show completed, show all, or show active.

The state of the visibility filter is a simple string representing the current filter. It is changed by set
visibility filter action.

To store this new information, I don't need to change the existing reducers. I will use the reducer
composition pattern and create a new reducer that calls the existing reducers to manage parts of its
state and combines the results in a single state object.

Now that the first time it runs, it will pass undefined as the state of the child reducers because the initial
state of the combined reducer is an empty object, so all its fields are undefined. This gets the child
reducers to return their initial states and populates the state object for the first time.

When an action comes in, it calls the reducers with the pass of the state that they manage and the
action and combines the results into the new state object.

11
This is another example of the reducer composition pattern, but this time we use it to combine several
reducers into a single reducer that we will now use to create our store. The initial state of the combined
reducer now contains the initial states of independent reducers. Any time an action comes in, those
reducers handle the action independently.

This pattern helps scale Redux's development because different people on the team can work on
different reducers handling the same actions without running into each other and causing merge
conflicts.

Finally, I'm dispatching the set visibility filter action. You can see that it doesn't affect the to dos, but the
visibility filter field has been updated.

Redux: Reducer Composition with combineReducers()

In the previous lesson we learned how to use the reducer composition pattern to let different reducers
handle different parts of the straight tree, and then combine their results.

This pattern is so common that it's present in most Redux applications. This is why Redux provides a
function called combineReducers that lets you avoid writing this code by hand. Instead, it generates the
top level reducer for you.

The only argument to combine reducers is an object. This object lets me specify the mapping between
the straight field names, and the reducers managing them. The return value of the combineReducer is
called a Reducer function, which is pretty much equivalent to the reducer function I wrote by hand
previously.

The keys of the object I configure combined reducers with correspond to the fields that the straight
object is going to manage. The values of the object I have asked to combineReducer, are the producers
we should call to update the correspondence straight fields.

This combineReducer call says that the ToDo's field inside the straight object managers will be updated
by the reduce-reducer, and the visibility filter field inside the straight object will be updated by calling
the visibility filter reducer. The results will be assembled into a single object. In other words, it behaves
pretty much exactly as the function commented down below.

Finally, I will establish a useful convention. I will always name my reducers after the straight keys they
manage. Since the key names and the value names are now the same, I can omit the values thanks to
the ES6 object literal shorthand notation.

In this lesson, you learned how to generate a simple reducer that calls many reducers to manage parts
of its tree by using the combineReducers utility function.

Redux: Implementing combineReducers() from Scratch

12
In the previous lesson, we learned to use the combine reducer function, which comes with Redux and
generates one reducer from several other reducers, delegating to them paths of the state tree.

To gain a deeper understanding of how exactly combined reducers works, we will implement it from
scratch in this lesson.

Combine reducers is a function, so I'm writing a function declaration. Its only argument is the mapping
between the state keys and the reducers, so I'm just going to call it Reducers.

The return value is supposed to be a reducer itself, so this is a function that returns another function.
The signature of the return function is a reducer signature. It has the state and the action.

Now, I'm calling the object key's method, which gives me all the keys of the reducer's object. In our
example, this is todos and the visibility filter.

Next, I'm calling the reduce method on the keys, because I want to produce a single value, such as the
next state, by accumulating over every reducer key and calling the corresponding reducer.

Each reducer passed through the combine reducers function is only responsible for updating a part of
the state. This is why I'm saying that the next state by the given key can be calculated by calling the
corresponding reducer by the given key with the current state by the given key and the action.

The [inaudible 1:46] reduce wants me to return the next accumulated value from the call back, so I'm
returning the next state. I'm also specifying an empty object as the initial next state, before all the keys
are processed.

There we have it. This is a working reimplementation of combined reducers utility from Redux.

Let's briefly recap how it works. I'm calling combined reducers with an object whose values are the
reducer functions and keys are the state field they manage. Inside the generated reducer, I'm retrieving
all the keys of the reducers I passed to combine reducers, which is an array of strings, todos and visibility
filter.

I'm starting with an empty object for my next state and I'm using the reduce operation of these keys to
fill it gradually.

Notice that I'm mutating the next state object on every iteration. This is not a problem, because it is the
object I created inside the reducer. It is not something passed from outside, so reducer stays a pure
function.

To calculate the next state for a given key, it calls the corresponding reducer function, such as todos or
visibility filter.

The generated reducer will pass through the child reducer only if part of its state by the key. If its state is
a single object, it's only going to pass the relevant part, such as todos or visibility filter, depending on the
current key, and save the result in the next state by the same key.

Finally, we use the array reduce operation with the empty object as the initial next state, that is being
filled on every iteration until it is the return value of the whole reduce operation.

13
In this lesson, you learned how to implement the combined reducers utility that comes with Redux from
scratch.

It is not essential to use in Redux, so it is fine if you don't fully understand how it works yet. However, it
is a good idea to practice functional programming and understand functions can take other functions as
arguments and return other functions, because knowing this will help you get more productive in Redux
in the long term.

Redux: React Todo List Example (Adding a Todo)

In the previous lessons, we learned how to split the root registers into many smaller registers that
manage parts of the stream tree.

We have a ready ToDo app register that handles all the actions of our simple ToDo application. Now it's
trying to implement the View layer. I'm going to use React in this example.

I'm adding react and redact dom packages from the Facebook CDM. I'm also adding a div with the ID
root, which is where I'm going to render my react application.

Similar to the react counter-example from the eighth lesson, I declare a render function that is going to
update dom in response to the current application state. I'm going to subscribe to these chore changes
and call render whenever there's store changes and wants to render the initial state.

The implementation of the render method is going to use react, so it's called react-dom render for some
to-do app component I haven't written yet. It renders it into the div I created inside the HTML. It's div
with the ID called "root".

React provides a base class for all components. I'm grabbing from the react object called
"reactComponent". I'm declaring my own ToDo app component that extends the react-based
component. This component is only going to have a render function and is going to return a div. Inside
the div, I'm going to place a bottom saying @ToDo them.

I don't want to add an input field yet to keep the example simple at first. I'm dispatching the out ToDo
action, and I'm going to put a test as my checks for the action. It's going to keep adding to this with the
products test.

The ID, I need to specify a sequential ID. This is why I'm declaring an global variable called "NextToID",
and I'm going to keep in command in it. Every time, it's going to emit a new idea.

I also want to display a list of the ToDo list. Assuming that I have the ToDos inject as ToDos prop, I'll call
map and for every ToDo item, I'm going to show a list item show in the text of that particular ToDo.

Finally, because I need to the ToDo as a prop, I'm going to pass it to the ToDo app by reading the
currents chores straight and written its ToDo field.

You can see that there is a button at ToDo and anytime I press it, I see a new ToDo with a test text. I'm
going to add an input inside my render function, and I'm using the react callback ref API where ref is a

14
function, it gets the note corresponding to the ref, and I'm saving that note with some name. In this
case, this test input.

I'm able to read the value of the input inside my event handler. I'm reading this job input that value. I'm
also able to reserve the value after dispatching the action so that the field is cleared. If I try write
something to build and press AddtoDo, the AddtoDo action is dispatched and the field is cleared.

Let's take a moment to recap how this application works. It starts with a ToDo app react component.
This component is not aware of how exactly ToDos are being added. However, it can express its desire
to meet a [indecipherable 4:04] by dispatching an action with the type ToDo.

For the text field, it uses the current input value and it passes an incrementing ID as the ID of ToDo.
Every ToDo needs its own ID, and in this approach, we're just going to increment the counter, so it
always gives us the next integer as ID.

It is common for react components to dispatch actions in Redux apps. However, it is equally important
to be able to render the current state. My ToDo app component assumes that it's going to receive ToDos
as a prop, and it maps over the ToDo list to display a list of them using the ID as a key.

This component is being rendered in the render function that runs any [indecipherable 4:53] changes
and initially. The render function reads the current state of this chore and passes the ToDos array that it
gets from the current state of this chore to do to the app component as a prop.

The render function is called on every store change so the ToDos prop is always up to date. This was the
rendering part of the redux flow. Let's recap how mutations work in Redux.

Any state change is caused by a store dispatch call somewhere in the component. When an action is
dispatched, this store calls the reducer it was created with, with the current state and the action being
dispatched.

In our case, this is the ToDo app reducer, which we obtained by combining divisibility filter and the
ToDos reducer.

It matches the action type and the switch statement. If the action type is add ToDo and indeed, it is
equal to add ToDo string. In this case, it will call the child ToDo reducer, passing it undefined, because
this is no state for a new ToDo that it can pass in the action.

We have a similar state statement inside the ToDo reducer and the action type is add to-do. It returns
the initial state of the to-do where the ID and text from the action and the completed field set to false.

The ToDos reducer that called it was returned a new array with all existent items and the new item
added at the very end. It adds a need to do to the current state.

Finally, the combined producer called ToDo app will use this new array as the new value for the to-dos
field in the global state object. It's going to return a new state object where the ToDos field corresponds
to the array with the newly-added ToDo item.

The ToDo app reducer is the root reducer in this application. It is the one the straw was created with. Its
next state is a next state of the Redux chore, and all the listeners are notified.

15
The render function is subscribed to the straw changes so it is called again, and it gets the fresh state by
call and gets state and it passes the fresh ToDos to the component, re-rendering it with the new
[indecipherable 7:24].

Redux: React Todo List Example (Toggling a Todo)

In the last lesson, we implemented a simple UI for the todo list application that is able to add new todos
and view the existing todos in the list.

To add the todos, we dispatched the add todo action. In this lesson, we're going to dispatch the toggle
todo action to toggle the completed state of the todos by clicking on them.

I'm scrolling down to my React component. I've got a list item here corresponding to the todo, so I'm
adding the on click handler. When the user clicks on the list item, I want to dispatch an action to my
store with a type toggle todo and the ID of the todo being toggled, which I get from the todo object.

The event handler knows which todo it corresponds to, so it is able to pass its ID in the action.

In the user interface, I want the completed todos to appear crossed out, so I'm adding this trial attribute
to the list item. I'm going to use the text decoration property, which is going to be a line through when
todo completed is true, and non when todo completed is false, so I get a normal looking todo.

Now, if I add a couple of todos, I can click on them and they're going to appear toggled, and I can toggle
them back. Isn't that satisfying?

Let's recap how toggling the todo actually works.

It starts with me dispatching the toggle todo action inside my click handler, with a type toggle todo and
the ID, which is the ID of the todo being rendered. I get the todo object as an argument to the array map
call back inside my render method where I render all the todos.

When an action is dispatched, the store will call the root reducer, which will call the todos reducer with
the array of todos and the action. In this case, the action type is toggle todo, so the todos reducer
delegates handling of every todo to the todo reducer with a map function to call it for every todo item.
The todo reducer receives the todo as state, and the action.

Again, we switch on the action type, and it matches toggle todo string. Now, for every todo whose ID
does not match the ID specified in the action, we just return the previous state, that is the todo object,
as it was.

However, if the ID of the todo matches the one specified in the action, we're going to return any object
with all the properties of the original todo, but with the completed field equal to the opposite value of
what it was.

The updated todo item will be included in the todos field under the new application state. Because we
subscribe, the render function is going to get the next state of the application in store -- get state -- and

16
pass the new version of the todos to the todo app component, which is going to render the updated
todos.

Finally, this trial of the list item, the bands on the todo completed field, which we just updated, which is
why it re-renders in a cross-child state.

Redux: React Todo List Example (Filtering Todos)

In the previous two lessons, we were working on creating the user interface for the to-do list application
that displays the to-dos, lets us add new to-dos, and toggle them on click. We implemented that by
dispatching at to-do and toggle to-do actions that we already know how to handle in our reducers.

In this lesson, we're going to dispatch set visibility filter reaction and use the visibility filter field to only
show the to-dos the user wants to see -- either the completed to-dos, active to-dos, or all to-dos in the
current state.

I'm starting by creating a new functional component called, "filter link" that the user needs to click to
switch the current visible to-dos. The filter link accepts the filter prop, which is just a string, and the
children, which is the contents of the link. It's going to be a simple A tag that doesn't really link
anywhere. It's going to prevent the navigation when clicked.

It's going to dispatch an action, the type, set visibility filter, and pass in the filter prop so that the
reducer knows which filter is being clicked. I will pass the children down to the A tag, so the consumer
can specify the text of the link. Now I can use it in my to-do app component.

Just below the to-do list, I am adding a paragraph where I'm going to offer the user the choice as to
which to-dos should be currently visible by using the filter link component I just created.

The filter prop is one of the three possible values, such as show all, which corresponds to showing every
to-do in the state, show active, which means just show the to-dos that are not completed yet, and show
completed, which means show the completed to-dos. I'm copy-pasting the filter link, and I'm changing
the labels and the filters corresponding to it.

Running this code will give me three different things under the list of to-dos. Clicking on them will
change the state visibility filter field. However, it doesn't have any effect yet because we don't interpret
the value of the visibility filter.

I am creating a new function that is going to help me filter the to-dos according to the filter value. It's
called, "get visible to-dos." It accepts two arguments, the to-dos and the filter. It switches on the current
filter value.

If the filter is show all, it's going to return all of the to-dos. But if the filter is show completed, it's going
to call to-dos.filter, that is array filter method, to only return those to-dos that have completed set to
true. Show active is going to the opposite of that. It's going to return only those to-dos where a
completed field is false.

17
Now I need to call this function to filter the to-dos before rendering them. In the render function of the
to-do app component, I get the visible to-dos by calling get visible to-dos with the to-dos and the
visibility filter values from my props. I'm going to use the visible to-dos instead of these props to-dos
when I enumerate them for rendering.

Finally, I now use the visibility filter inside my to-do app component, so I need to pass it as a prop.

I could do this explicitly, but actually it's easier for me just to spread over all the straight fields. So every
straight field inside the state object is passed as a prop to the to-do app component. This way, it
receives the visibility filter. If I add some to-do items and then click on them, so I change their completed
fields, and then click on the visibility filter links, the currently visible to-dos are rendered according to
the chosen visibility filter.

The links look all the same right now, but we want to highlight the chosen one. To implement this, we're
going to need the visibility filter prop which says which is the current one.

I'm changing the beginning of the render method to destructure the to-dos and the visibility filter from
the props, so I can access them directly now without typing this .props every time. I'm going to pass the
visibility filter to every filter link, so it can know which filter is the current one and apply different styling
if the current filter matches the filter links' own filter.

After passing the current filter prop to every filter link, I go back to the filter link declaration. I'm adding
current filter as a prop to it, and I'm adding a condition that says that when the filter is the current filter,
that is, when the link is active, I want to return a span instead of a link because I don't want it to be
clickable. I want it to be static text.

This completes the user interface of our to-do list example. It lets us add items. It lets us view items,
toggle them as completed. When we switch the visibility filter, it displays only relevant to-dos, and it
also updates the link appearance, so we see which link is active.

Let's recap how a change in the visibility filter works. It starts with a dispatch code with an action of the
type set visibility filter. It passes filter, which is a prop, to the link component, so every one of those
three links is going to have a different filter prop it passes in the action.

The store dispatch function will call our root reducer with the state and the action which in turn will call
the visibility filter reducer with the part of the state and the action.

Note that when the action type is set visibility filter, it doesn't care for the previous state, it just returns
the action filter as the next value, the next state, of the visibility filter reducer. The root reducer will use
this new field as part of its new state object.

Because the render function is subscribed to the stored changes, it's going to get this new state object
and pass all its keys as props to the to-do app component. The to-do app component will receive the to-
dos and the updated visibility filter as its props.

Both these props are passed through the get visible to-dos function, which calculates the currently
visible to-dos according to a list of all to-dos and the visibility filter. The filter is just a string saying show
all, completed, or active.

18
The return value is a new array of to-dos that in some cases, filters them and, in some cases, returns as
is. The show completed and show active are only different in their predicates.

The return value is the array of visible to-dos. It is used in the render function to actually enumerate
every to-do and render it.

The visibility filter field is also used by the filter links as the current filter because the filter link wants to
know whether its filter is the current one in order to render a span instead of a link. This is how clicking
a link makes it appear selected and changes the currently displayed items in the list.

Redux: Extracting Presentational Components (Todo, TodoList)

In the last few lessons, we created user interface for a simple React and Redux to-do list where I can add
items, toggle them as completed, and change the currently visible to-dos.

We do that by having a single to-do app component that has the input, the button for adding to-dos, the
list of currently visible to-dos with click handler. It has this three links that let us change the currently
visible to-dos.

The single component approach worked so far. However, we really want to have many components that
can be used, tested, and changed by different people separately. So we're going to refactor our
application in this lesson.

The first component I want to extract from the to-do app component is the to-do component that
renders a single list item. I am declaring the to-do component as a function which React 14 allows me to
do. I'm not sure which props it's going to have, so I'll leave them blank for now. I will just paste the list
item I covered before.

The first thing I'm doing is removing the special key property because it's only needed when I enumerate
an array. I'll use it later when enumerating many to-dos.

One of my goals with this refactoring is to make every component as flexible as it is reasonable. Right
now, I have hardcoded that clicking a to-do always causes the toggle to-do action. This is perfectly fine
to do in your app.

However, I prefer to have a bunch of components that don't specify any behaviors, and that are only
concerned with how things look or how they render. I call such components the presentational
components.

I would like to give to-do a presentational component, so I removed the on click handler. I promote it to
be a prop so that anyone who uses to-do component can specify what happens on the click. You don't
have to-do this in your Redux apps, but I find it to be a very convenient pattern.

Finally, while it doesn't have a lot of difference, I prefer to keep it explicit what is the data that the
component needs to render. Instead of passing a to-do object, I pass completed and text fields as
separate props.

19
Note how the to-do component is now a purely presentational component and doesn't specify any
behavior. But it knows how to render at to-do.

The next component I create is called to-do list. It's also a presentational component. It's only concerned
with how things look.

It accepts an array of to-dos. It's going to render an unordered list of them by calling the to-dos map
function and rendering at to-do component for every to-do. It tells React to use to-do ID as the unique
key for the elements. It spreads over the to-do object properties so the text and completed end up as
props on the to-do component.

I need to specify what happens when a to-do is clicked. I could have dispatched an action here. Again,
that would be fine, but I want it to a presentational component, so I'm going to call another function,
called on to-do click, and pass the ID of the to-do, and let it decide what should happen. On to-do click is
another prop for the to-do list.

Both to-do and to-do list are presentational components, so we need something I call, "container
components" to actually pass the data from this chore and to specify the behavior. In this case, the top
level to-do app component acts as a container component. We will see more examples of container
components in the future lessons.

In this case, it just renders the to-do list with visible to-dos as the to-dos, and with a callback that says
that when on to-do click is called with a to-do ID, we should dispatch an action on the chore with the
type toggle to-do and the ID of the to-do.

Let's recap again how this works. The do to app component renders a to-do list, and it passes a function
to it that can dispatch an action. The to-do list component renders the to-do component and passes on
click prop which calls on to-do click.

The to-do component just uses the on click prop it receives and binds it to the list item on click. This
way, when it's called, the on to-do click is called, and this dispatches the action and updates the visible
to-dos because the action updates the store.

Redux: Extracting Presentational Components (AddTodo, Footer,


FilterLink)

In the previous lesson, I extracted the to-do and to-do list components from the to-do app component.
In this lesson, I will continue extracting other presentational components to separate the looks from the
behavior.

Now I want to extract the input and the button into a separate component called, "at to-do." I'm
declaring at to-do as a functional component that doesn't accept any props. I'm going to return these
copy pasted input in button, but I'm wrapping them in a div because a component needs to have a
single root element.

20
The functional components don't have instances. However, instead of using this, I can use a local
variable called, "input," that I'm going to close over so I can write to it in the callback graph and I can
read from it in the event handler.

Like previously, I want it to be a presentational component and not specify behavior, so I just called the
function called, "on at click," passing the current input value. I make on at click a prop so that the
component that uses at to-do can specify what happens when that button is clicked.

Again, the to-do app component acts as a container component for the at to-do. It specifies that when
add button is clicked, we should dispatch an action with the type at to-do, the corresponding text, and
the next to-do ID.

The last component I want to extract today is the footer, which contains all these three filter links. I'm
creating a new functional component called, "footer." I'm not sure which props it needs, so I skip them. I
paste the markup. It seems that the filter link need the visibility filter, so I add it as a prop.

I would like the footer and the filter link to be presentational components. However, the filter link
includes a short dispatch call. I am replacing it with an on click call. I pass the filter as the single
parameter for the calling component's convenience. I add on click to the props.

Now I need to specify it every time filter link is used. I add on filter click to the footer. I pass on click
equals on filter click for every filter link in the footer, so whatever we pass to the footer as on filter click
prop is going to end up in the filter link as on click.

Now I can use the footer component I just defined inside my to-do app component. I need to pass to
props, one of them is the visibility filter so it can highlight the active link. Another prop is on filter click
where I say that whenever a filter is clicked, I want to dispatch an action with a type set visibility filter
and the filter being clicked.

Finally, I just noticed that the to-do app component doesn't actually have to be a class. I can turn it into
a function. I prefer to-do that when possible.

Instead of destructuring the props inside the render method, I am now doing it inside the argument. I
can remove now the destructuring. I'm also going to remove the render method declaration. The visible
to-dos are only used in a single place, so I'm moving the get visible to-dos call to the to-do list to-dos
prop declaration. Now the body of my function is just a single expression, so I can get rid of the return
statement and unintended code to make it look nicer.

This concludes the initial refactoring of the to-do list application into a single container component
called to-do app and many presentational components that are only concerned with how things look.
Let's recap the data flow in this example.

We have a single container component called to-do app. We re-render it any time the store changes. It
receives the keys of the global state object as the props, so it receives the to-dos and the visibility filter
values.

The first component it renders is called at to-do. At to-do is a presentational component that renders an
input and a button. When the button is clicked, it passes the current input value to the on app click
function.

21
On app click function is a prop for the at to-do component. In this case, it is specified by the to-do app,
which says that when the button is clicked, it should dispatch an action containing the current text in the
action object. Dispatching the at to-do action will call our reducer, update this chore state with the new
to-dos, and re-render the do app component with the new to-dos.

The to-dos themselves are rendered by the to-do list presentational component that receives two props,
the currently visible to-dos and the on to-do click callback.

The to-do list component receives an array of to-dos, and it maps over them, rendering individual to-do
components. It uses the spread operator to pass every property of the to-do object as a prop to to-do
component. It specifies the on click handler as calling on to-do click with the ID of the particular to-do.

The to-do component is defined above. It is also a presentational component, so it doesn't specify the
behavior. It says that when a list item is clicked, it should call the on click handler. Being a presentational
component, it specifies how the component looks in different circumstances. In this case, it uses the
completed prop to choose between two different styles of the to-do item.

The to-do list is also presentational component. It delegates actually handling the click to on to-do click
prop. It passes the ID of the to-do being clicked.

Finally, the to-do app component reacts to it by dispatching an action containing the ID of the to-do
clicked and the type toggle to-do. The store will call our reducer and update the state of the application,
re-rendering the to-do app component with the new to-dos.

The footer component receives the current visibility filter as a prop and also receives the on filter click
callback that sets the current visibility filter. The footer component renders three filter links, passing
down their respective filter values, the on click handler, and the current visibility filter.

The filter link component being a presentational component doesn't know what to-do when it's clicked,
so it calls the on click callback, passing the filter, which is different for each of those links, as an
argument. The footer delegates handling the click of the filter link to its own prop, called on filter click.

Finally, the to-do app component being the container component in our application specifies the
behavior, which in this case means that when the filter link is clicked, it should dispatch an action with
the type set visibility filter, and the new filter.

Separation of the presentational components is not required in Redux, but I recommend this pattern
because it decouples your rendering from Redux. So if you later choose to move your project to another
framework, such as Relay, you will not have to change all your components because you can keep the
presentational components exactly the same.

This approach also has downsides, such as that you have to thread a lot of props through the
components to get them to the list components, including the callbacks. This problem can be easily
solved by introducing many intermediate container components as we will see in the next lesson.

Redux: Extracting Container Components (FilterLink)

22
In the previous lesson, we separated the presentational components from the main container
component. The to-do app specifies the behaviors, which is what happens when add button, how the
to-dos are selected, what happens when a single to-do is being clicked, and what happens when a footer
link is clicked.

The components, such as at to-do, the to-do list, the to-do itself, the footer, and the filter link, they
don't dispatch actions. They call their callbacks in the props. They are only responsible for the looks but
not for the behavior.

The downside of this approach is that I have to pass a lot of props down the tree even when the
intermediate components don't really use them.

For example, the filter link needs to know the current filter so that it can choose a different appearance
when it is active. However, in order to receive the current filter, it has to be passed down from the top.
This is why the footer has to accept visibility filter as a prop, so it can pass it down as a current filter to
the filter link.

In a way, this breaks encapsulation because the parent components need to know too much about what
data the child components need. To solve this, we're going to extract a few more container components,
just like we extracted the presentation components in the previous lesson.

The first component I'm going to refactor is the footer component. Currently, it accepts two props -- the
visibility filter, and the on filter click callback. But it doesn't actually use either of them. It just passes
them down to the filter link. This seems like a good opportunity for simplification.

We can only do this because we know that the footer component doesn't care about the values of these
props. They only exist to be passed down to the filter link that cares about them.

I am removing the props definition, and I'm removing these props from the filter link usage. It might
start to seem a lot like the the code before separating the presentational component. However, what I
want to here is a little bit different.

The filter link does not currently specify the behavior for clicking on the link. It also needs the current
filter to tell whether it should be rendered as active.

Therefore, it's a bit dishonest to say that filter link is a presentational component because it is
inseparable from its behavior. The only reasonable reaction to clicking on it is setting the visibility filter
by dispatching an action.

This is why I'm changing it to a different presentational component I'm going to call, "link." I will create
another filter link component as a container that uses it for rendering. The link component doesn't know
anything about the filter. It only accepts the active prop, and it calls its own click handler. It is only
concerned with rendering.

However, I'm also creating another component, called, "filter link." It is going to be a class this time that
is going to render the link with the current data from this chore. It's going to read the component props,
and it's going to read the state. But I don't mean react state. I mean the Redux chore state it gets by
calling, "store get state."

23
As a container component, the filter link doesn't have its own markup. It delegates rendering to the link
presentational component. In this case, it calculates its active prop by comparing its own filter prop with
the visibility filter in the Redux chore state. The filter prop is the one that is passed to the filter link from
the footer. The visibility filter corresponds to the currently chosen visibility filter that is held in Redux
chore state. If they match, we want the link to appear active.

The container component also needs to specify the behavior. In this case, the filter link specifies that
when this particular link is clicked, we should dispatch the action with the type set visibility filter and the
filter value that we take from the props.

The filter link may accept children which are used as the contents of the link, so we're going to pass the
children down to the link component. We're just going to render them inside the A tack.

There is a small problem with this implementation of filter link. Inside the render map, it reads the
current state of the Redux chore. However, it does not subscribe to this chore. If the parent component
does not update when this chore is updated, it's going to render this tail value.

Currently, we rearrange the whole application when the state changes. However, this is not very
efficient. In future, we will instead move subscription to this chore, to the lifecycle methods of the
container components.

React provides a special force update method on the component instances to force their re-rendering.
We're going to use it together with chore subscribe method so that any time the store state changes, we
force update the container components.

We perform the subscription inside the component if mount lifecycle method. So it's important to
unsubscribe inside the component will unmount method. Note that we don't actually have the
unsubscribe function, but this is the return value of the store subscribe method, so we can keep it, and
then call it inside component will unmount.

Let's recap this part. The filter link component subscribes to this chore, calling force update any time this
chore changes so it can render the current state of this chore. It saves the reference through the
unsubscribe function returned by store subscribe. It invokes it when the component is about to
unmount to clean up the subscription.

Let's recap the relationship between the filter link container component and the link presentational
component. The link component only specifies the appearance of the the link, when it is active or
inactive, but it doesn't know about the behavior. The filter link component is a container, so it provides
the data and the behavior for the presentational component.

When it mounts, it subscribes to this chore, so it independently re-renders when the store state changes
because it needs to use this chore current state inside its render method.

Instead of specifying the DOM tree, it delegates all the rendering to the link presentational component.
Its only job is to calculate the props based on the filter link's own props and the current state of the
Redux chore. It also specifies the callbacks that are going to dispatch the actions on this chore.

After the action is dispatched, this chore will remember the new state returned by the reducer and will
call every subscriber to this chore. In this case, every filter link component instance is subscribed to this

24
chore, so they will all have their force update methods called on them. They will re-render according to
the current chore state.

The filter link is a container component, so it is completely self-sufficient and can be used inside the
presentational components, such a footer, without passing additional props to get the data from this
chore and specify the behavior. This lets us keep the footer component simple and decoupled from the
behavior and the data that its child components need.

Redux: Extracting Container Components (VisibleTodoList, AddTodo)

In the previous lesson, I separated the link presentational component from the filter link container
component that is subscribed to the Redux chore and that provides the data and the behavior for the
link component it renders.

While it makes the data flow a little bit less explicit, it makes it easy to use filter link in any component
without worrying about passing additional data to the filter link or to the component that contains it. In
this lesson we'll continue extracting the container components from the top level container component.
The first candidate is the ToDoList component.

I actually want to keep the ToDoList presentational component. However, I want to encapsulate within
the currently visible ToDos this into a separate container component that connects the ToDoList to the
Redux chore. I'm going to call this component the visible ToDoList.

Just like when declaring the filter link component in the previous lesson, I calculate the data from the
current component by using the current state which is the state from the Redux chore. I'm using the get
visible ToDos function to calculate the currently visible ToDos based on all the ToDos from the Redux
chore and the current visibility filter from the Redux chore state. I'm specifying the behavior as well. I'm
seeing that when the ToDo is clicked, we should dispatch an action [inaudible 1:32] type toggle ToDo
and the ID of the ToDo being clicked.

All container components are similar. Their job is to connect a presentational component to the Redux
chore and specify the data and the behavior that it needs. I'm scrolling up to the filter link container
component I wrote in the previous lesson to copy-paste this chore subscription logic.

Just like the filter link, the visible ToDoList is going to subscribe to this chore and force an update any
time this chore state changes because it uses this state in its render method. Now that the visible
ToDoList is connected to the Redux chore, we can use it instead of the TodoList. We no longer have to
pass all the props from the top.

Finally, in the previous lesson, I made app ToDo a presentational component, but I'm going to backtrack
on this now. I will copy-paste the dispatch call back in line into the onClick handler inside the component
because there isn't really a lot of presentation or behavior here.

25
It's easier to keep them together until we figure out how to split the presentation. For example, if in the
future, we're going to have something like a form component, we may split it, but for now we'll keep
them together.

I'm scrolling down to my ToDo app component. I'm removing the onAuth click prop. I just noticed that
none of the containers actually need any props from this street. I can remove the props of the ToDo app
component. I can remove the render function that renders the ToDo app component with the current
street of this chore because I can just call it once, remove all the props that are related to this state and
just render it as is because the container components that I render are going to subscribe to this chore
themselves and are going to update themselves when this chore state changes.

Let's recap the data flow after separating the presentational and the container components. There is
just one react on render call at the very end. We don't render again when this chore state changes
because the container components take care of that.

The first component I'm looking at is called a ToDo. Frankly, I can classify it either as a presentational
component or as a container component because it doesn't fit either category. The input and the button
are the presentational part, but dispatching an action onClick is the behavior which is usually specified
by the container.

However, in this case, I'd rather keep them together because there isn't any street, the UI is very simple.
It's hard to imagine any other behavior other than dispatching the at ToDo action.

The second component are rendering inside the at To-Do app is called the visible ToDoList. This time, it
is a proper container component that subscribes to this chore and re-renders the ToDoList any time this
chore state changes. It calculates the visible ToDos from the current Redux chore street, the ToDos and
the visibility filter fields. It passes them as the To-Dos.

When the To-Dos are clicked, it's going to dispatch an action with the type [inaudible 4:58] ToDo and the
ID of the respective ToDo. The actual rendering here is performed by the ToDoList component that just
renders the ToDos passed through it as prop and binds their clicks through the on ToDo click prop.

Finally, the last component ToDo app renders is the footer. The footer is just a presentational
component rendering three different filter links. The filter link is a container component. It subscribes to
this chore and it renders the presentational component called, "link," calculating whether it should be
active based on its props and the current Redux chore street and specifies the behavior what happens
when it's clicked.

Finally, the link component is just a presentational component that render a-check. Separating the
container and the presentational components is often a good idea, but you shouldn't take it as a dogma.
Only do this when it truly reduces the complexity of your code base.

In general, I suggest first trying to extract the presentational components. If there is too much
boilerplate passing the props through them, then you can create the containers around them that load
the data and specify the behavior.

26
Redux: Passing the Store Down Explicitly via Props

In the previous lessons, we used this tool to up level variable to refer to the Redux chore. The
components that access this chore, such as the container components, read this straight from it,
subscribe to this chore, and dispatch actions on this chore using this chore top-level variable.

This approach works fine for JS bin example where everything is in a single file. However, it doesn't scale
to real applications for several reasons.

First of all, it makes your container components harder to test because they reference a specific chore,
but you might want to supply a different marks chore in the test. Secondly, it makes it very hard to
implement universal replications that are rendered on the server, because on the server, you want to
supply a different chore instance for every request because different requests have different data.

I'm going to start by moving this chore creation code to the bottom of the file where I render my React
components. I'm going to change it slightly. Instead of creating this chore top-level variable, I will pass
this chore I create as a prop to the top-level component, so it is completely injectable into it.

Every container component needs a reference to this chore so unfortunately, we have to pass it down to
every component as a prop. It's less effort than passing different data through every component, but it's
still inconvenient. So, don't worry, we'll find a better solution later, but for now, we need to see the
problem.

The problem is that the container components need to have this chore instance to get this straight from
a dispatch actions and subscribe to the changes. This time, I'm changing the container component to
take this chore from the props using the ES6 destruction syntax, which just means "chore equals props
does chore."

I'm doing the same here. I'm just taking this chore from the props so I can call dispatch on it.

I need to make similar changes to other container components. In this case, I have this at to-do
component, which is not exactly a container component, but it still needs its chore to dispatch the at to-
do action, so I added it as a prop. I'm also going to add this chore to the photo component because,
unfortunately, filter link needs it.

The photo component renders filter link. This is not convenient, but as I said, we'll figure out a way to
avoid this later. For now, we need to pass this chore down so that every container component, such as
filter link, can use it to subscribe to the changes, to read this state and to dispatch actions without
relying on a top-level variable being available.

I'm changing the render method to read this chore from the props. Now, all containers read this chore
instance from the props, and don't rely on a top-level variable that I removed.

Note that this change did not change the behavior or the data flow of this application. The container
components subscribe to this chore, just like before, and update their state in response to its changes.

27
However, what changed is how they access this chore. Previously, they would access a top-level
variable, but this approach does not scale to real-world applications. This is why, right now, I'm passing
down this chore as a prop, so the container components can subscribe to it.

In the future lessons, we will see how to pass this chore down to the container components implicitly
but without introducing the top-level variable.

Redux: Passing the Store Down Implicitly via Context

In the previous lesson, we got rid of the top level chore variable and instead starting passing this chore
as a prop to the to-do app component. So every component below receives this chore as a prop. We
even have to do this for presentational components because sometimes they contain container
components that need this chore to subscribe to the changes.

We have to write a lot of boiler plate code to pass this chore down as a prop. But there is another way,
using the advanced React feature called context.

I'm creating a new component called provider. From its render method, it just returns whatever its child
is. We can wrap any component in a provider, and it's going to render that component.

I'm changing the render call to render a to-do app inside the provider. I'm moving this tool prop from
the to-do app to the provider component. The provider component will use the React advanced context
feature to make this chore available to any component inside it, including grandchildren.

To do this, it has to define a special method get child context that will be called by React by using this
props tool which corresponds to this chore that is passed to the provider as a prop just once.

This tool will be part of the context that the provider specifies for any its children and grandchildren. The
to-do app is going to receive this context, and any component inside to do app is also going to receive
this context object with this tool inside it.

However, there is an important condition for the context to work. This condition is that you have to
specify child context types on the component that defines get child context. These are just React prop
types definition, but unlike prop types, the child context types are essential for the context to be turned
on. If you don't specify them, no child components will receive this context.

The container components currently access tool by props, but we're going to change this to read this
chore from React context. To do that, we just wrap it to this.context. Similarly, in the render method, I'm
also going to read this chore from the context instead of the props.

Finally, the context is opt-in for the receiving components, too, so you have to specify a special field
called context types, which are similar to child context type. But, in this case, we are specifying which
context we want to receive and not pass down. If you forget to declare the context types, the
component will not receive the relevant context, so it is essential to remember to declare them.

28
What about the functional components that don't have this? It turns out that they also receive the
context but as a second argument after the props. I'm destructuring the second argument and getting
this chore from there. The second argument is the context.

Just like with the class components, I still have to add a property called, "context types" that specifies
which context I want to receive. In this case, I want to receive the chore from the provider. If I forget to
declare the context types, my functional component will not receive the relevant context as a second
argument. It's important to remember to declare them any time you use the context.

Finally, I'm replacing the props with the context when getting this chore for the filter link. I'm adding the
context type declaration to the filter link so it receives the relevant context from the provider.

Now that the filter link receives this chore by context, I no longer need to pass it as a prop, so I'm
removing its usage. I'm also removing the store prop from the footer because it doesn't need to pass it
down anymore. I'm also removing this chore prop from the to-do app component because I no longer
need to pass it down to the containers.

Now, instead of explicitly passing this chore down by props, we pass it implicitly by context.

Let's recap how we use the context to pass this chore down. We start by rendering the to-do app inside
the provider component we defined above. The provider component just renders whatever you pass
through it. In this case, it renders its children or the to do app component. However, it also provides the
context to any components inside it including grandchildren.

The context contains just one key called the store. It corresponds to the store we passed as a prop to the
provider component.

We pass this chore to the provider component in our render code and make it available to child
components by defining the get child context with the store key pointing to that prop.

It is essential that the get child context is matched by child context types where we specify that the
store key has prop type of object. Note that the child context types definition is absolutely required if
you want to pass the context down the tree.

The benefit is that we don't need to pass this chore through the intermediate components. Instead, we
can declare the context types on the container components that need access to the store so that they
can retrieve it from the context instead of retrieving it from the props.

The context creates something like a wormhole between the visible to-do list component that reads the
context and the provider that provides the context. This wormhole is only enabled because the context
types declared on the visible to-do list include this chore that is defined in child context types of the
provider component.

The at to-do is another component that needs access to this chore. It also opts into receiving it in the
context by specifying the context types. This is why, in addition to props, it receives a second argument,
which is the context. I'm using the destruction syntax to grab this chore from the context here.

The context works at any depth, so it is not necessary to put context types on the footer. The filter link is
the component that directly uses the context, so this is the component that has to specify the context
types so that it can use this chore by reading it from the context.

29
Context is a powerful feature, but in a way it contradicts the React philosophy of the explicit data flow.
The context essentially allows global variables across the component tree. But global variables are
usually a bad idea. Unless you're using it for dependency injection, like here when we need to make a
single object available to all components, then probably you shouldn't use context.

Finally, the context API is not stable in React. It has changed before, and it is likely to change again. Try
your best not to rely on it too much.

Redux: Passing the Store Down with <Provider> from React Redux

In the previous session, we implemented the provider component that uses the react advanced context
feature to make this tool from the props available to every component in our rev.

If we pass it through the provider, we can read it in any other component from the context, which is
really convenient for the container components. In fact, this is so convenient that you don't need to
actually write the provider yourself, because it is included in a special library called React-Redux.

Note that it is not the same as Redux. This is a different library. These are react bindings to the Redux
library. You can import the provider by destructuring the react-redux global object in JS bin, or if you use
Babbel, and something like NPM, you can import provider with the braces, because it's a named expert
from React-Redux package. Or if you write ES5 code, you can write var provider equals require react
redux, or react redux global.provider.

Just like the provider we wrote before, the provider that comes with react-redux exposes this store you
passed through. There's a prop on the context so the components can specify the context types, and
then use this context store to subscribe to the store updates and dispatch actions.

Redux: Generating Containers with connect() from React Redux


(VisibleTodoList)

In the previous lesson, I added React Redux bindings to the project and I used a provider component
from React Redux to pass this chore down the context so that the container components can re-dischore
from the context and subscribe to these changes. All container components are very similar.

They need to re-render when the straw state changes, they need to unsubscribe from the straw when
they amount and they take the current state of the Redux chore and use it to render the presentational
components with some props that they calculate from the state of this chore, and they also need to
specify the context stripes to get this chore from the context.

I'm going to write this component in a different way now. I'll declare a function called
"MapsStateToProps" which takes the redux chore state and returns the props that I need to parse
through the presentation to do this component, to render it with the current state.

30
In this case, there is a single prop called ToDo. I copy-paste this expression to the MapStateToProps
function. It returns the props that depend on the current state of the redux chore. In this case, this is
just the ToDo list prop.

I'm creating another function that a core map dispatched the props. It accepts the dispatch method
from this chore as the only argument and returns the props that should be parsed through the list
component and that depend on the dispatch method.

The only prop that uses chore dispatch is called OnToDo click. Some copy-paste onto the click, into map
dispatch the props. Now that I don't have the reference to this chore here anymore. Instead, I'm
changing it to use the dispatch, which is provided as an argument to map dispatch the props.

I will add some punctuation to make it appear easier on my eyes. OnToDo click ease of function that
accepts the ID of the ToDo, and dispatches an action. Now, I've got two different functions.

The first one maps the redux chore state to the props of the ToDo list component that are related to the
data from the redux chore. The second function maps the dispatch method of this chore to the callback
props of ToDo list component. It specifies the behavior which callback prop dispatches which action.

To gather this, your function has described a container component so well that instead of writing it, I
can generate it by using the connect function provided by react redux library. If you use Babble and
NPM, you will likely input it like this instead. Don't forget the curly braces.

Now, instead of declaring a class, I'm going to declare a variable. I will call the connect method to obtain
it. I'm parsing MapsStateToProp as the first argument and MapDispatchTheProps as the second
argument. Notice that this is a correct function, so I have to call it once again. This time, I parse the
presentational component that I wanted to wrap and parse the props to you.

The connect function will generate the component, just like the one I previously wrote by hand. I don't
need to write the code to subscribe to this chore or to specify the context stripes, because the connect
function takes care of that.

Now, let's recap how to generate the container component using the connect function. First, I'll write a
function called MapStateToProps that takes the state of the redux chore and returns the props for the
presentational component calculated from it.

These props will be updated anytime the state changes. Next, I write a function that I call
MapDispatchTheProps. It takes these chores dispatch method as its first argument. It returns the props
that used the dispatch method to dispatch options, so it returns the callback props needed for the
presentational component.

To create the container component from them, I import connect from the react redux library and I call it
parsing MapsStateToProps as the first argument and will dispatch the props as a second argument.

Finally, I close the function called Param and I open another param, because this is a parent function and
it needs to be called twice. The last argument is the presentational component that I want to connect to
the redux chore.

31
The result of the connect call is the container component that is going to render my presentational
component. It will calculate the props to pass through the presentational component by merging the
objects returned from MapStateToProps, map dispatched to props, and its own props.

Redux: Generating Containers with connect() from React Redux


(AddTodo)

n the previous lesson, we used the connect function from React Redux bindings library to generate the
container component that renders our presentational component. I specify how to calculate the props
to inject from the current Redux chore state and the callback props to inject from the dispatch function
on the Redux chore.

Normally, I would keep these functions, call map state to props and map dispatch to props, but I'm
working in a single file right now. I need to write these functions for if your other container components,
so I'm going to rename them to something more specific, which you don't have to do in your code if you
keep every component in its own file.

I will also remove the line breaks here to make it clear that these functions are only relevant for
generating this particular container component.

Now I'm scrolling up to the at to-do component, which is not clearly presentational or a container
component. However, it uses this chore. It reads this chore from the context to dispatch an action when
the button is clicked. It has to declare the context types to be able to grab this chore from the context.

Context is an unstable API, so it's best to avoid using it in your application code. Instead of reading this
chore from the context, I will read the dispatch function from the props because I only need the
dispatch here. I don't need the whole chore.

I will create a container component with connect that will inject that the dispatch function as a prop. I
will remove the context types because the component generated by connect function will take care of
reading this chore from the context.

Because I changed the at to-do declaration from the const to the let binding, I can reassign it now so
that the consuming component does not need to specify the dispatch prop because it will be injected by
the component generated by the connect code.

The first argument to the connect function is map straight to props, but there aren't any props for at to-
do component that depend on the current state, so I return an empty object. The second argument to
connect is map dispatch to props, but at to-do component doesn't need any callback props. It just
accepts the dispatch function itself, so I'm returning it as a prop with the same name.

Finally, I'm calling the function for a second time to specify the component I want to wrap, in this case,
at to-do itself. The generated container component will not pass any props dependent on the state, but
it will pass dispatch itself as a function so that the component can read from the props and use it
without worrying about context or specifying context types.

32
However, it is wasteful to even subscribe to this chore if we don't calculate any props from its state. So
I'm replacing the maps straight to props function with an O, which tells connect that there is no need to
subscribe to this chore.

Additionally, it's pretty common pattern to inject just the dispatch function. This is why if you specify
null or any false value in connect as the second argument, you're going to get dispatch injected as a
prop. In fact, I can just remove all arguments here. The default behavior will be to not subscribe to this
chore and to inject just the dispatch function as a prop.

Let's recap what happens to the components here. The at to-do component that I declare accepts
dispatch as a prop, but it doesn't know how to get this chore. It just hopes that someone is going to pass
the dispatch to it.

The connect code without any arguments is going to generate a container component that does not
subscribe to this chore. However, that will pass dispatch to the component that it wraps. In this case, it
wraps my at to-do component.

The second connect call returns the generated container component. I'm assigning it to at to-do. I'm
reassigning the let binding the second time.

When the further code references at to-do, it's going to reference the container component that does
not need the dispatch prop and that will pass the dispatch prop to my inner at to-do component that I
don't have a reference to anymore.

Redux: Generating Containers with connect() from React Redux


(FooterLink)

Finally, let's take a look at the filter link container component that renders a link with an active property
and a click handler. First, I will write the map state to props function, which I'll call, "maps straight to link
props," because I have everything in a single file.

It's going to accept the state of the Redux chore and return the props that should be passed to the link.
We only have a single such prop called, "active" that determines whether the link displays the current
visibility filter.

When I paste this expression from the render method, I see that it references the filter prop of the filter
link component. To tell whether a link is active, we need to compare this prop with the visibility filter
value from the Redux chore sheet.

It is fairly common to use the container props when calculating the child props, so this is why props are
passed as a second argument to "map straight to props." I will rename it to "own props" to make it clear
we are talking about the container component's own props and not the props that are passed through
the child, which is the return value of "map straight to props."

33
The second function I'm writing here is "map dispatch to props" or, to avoid name clashes in this JS bin,
"map dispatch to link props." The only argument so far is the dispatch function. I'm going to need to
look at the container component I wrote by hand to see what props depend on the dispatch function.

In this case, this is just the click handler where I dispatch the set visibility fill direction. The only prop I'm
passing down is called, "on click." I declare it as an arrow function with no arguments, and I paste the
dispatch code. But it references the props again, so I need to add "on props" as an argument, the second
argument, to map dispatch to props function to you.

Finally, I will call the connect function from React Redux library to generate the filter link container
component. I pass the relevant "maps straight to props" function as the first argument, the "map
dispatch to props" as the second argument, and I call the function again with a link component which
should be rendered. Now I can remove the old filter link implementation.

Let's recap the data flow in this example. The photo component renders three filter links, and each of
them has a different filter prop that specifies which filter it corresponds to. This prop will be available on
the "on props" object that both "map dispatch to props" and "map straight to props" will receive as the
second argument.

We pass these two functions through the connect call, which will return a container component called,
"filter link." The filter link will take the props that will return from the "map dispatch to props" and "map
state to props" and pass them as props to the link component that it wraps.

We can now use the filter link container component and specify just the filter, but the underlying link
component will have received the calculated active and on-click values.

Redux: Extracting Action Creators

So far we have covered the container components, the presentational components, the reducers, and
the store. But we have not covered the concept of action creators, which you might see in the Redux
talks and examples.

Let's consider the following example. I dispatched the add todo action from inside the button click
handler. This is fine. However, it references the next todo ID variable, which added there alongside the
add todo component.

Normally, it would be local. However, what if another component wants to dispatch the add todo
action? It would need to have the access to next todo ID somehow. While I could make this variable
global, it's not a very good idea.

Instead, it would be best if the components dispatching the add todo action did not have to worry about
specifying the ID. Because the only information they really pass is the text of the todo being added.

I don't want to generate the ID inside the reducer, because that would make it non-deterministic.
However, I can extract this code generating the action object into a function I will call add todo.

34
I pass the input value to add todo. Add todo is just the function that takes the text of the todo and
constructs an action object representing add todo action. It has the type, add todo, it takes care of
generating the unique ID and it includes the text.

Although extraction such functions is not required, it is very common pattern in Redux applications to
keep them maintainable, so, like all these functions, action creators, and we usually place them
separately from components or from reducers.

I will now extract other action creators from the components. I see that I have it set visible to filter the
dispatch there, so I will change this to call this set visible the filter action creator with own props filter as
the argument and is going to return the action that needs to be dispatched, so I'm declaring this set
visible to filter function.

This is what I call an action creator, because it takes the arguments about the action and it returns the
action object with the type set visible to filter and the filter itself.

You might think that this kind of code is boilerplate and you'd rather dispatch the action in line inside
the component. However, don't underestimate how action creators document your software, because
they tell your team what kinds of actions the components can dispatch, and this kind of information can
be invaluable in large applications.

I will now scroll down to the last place where I call dispatch with an inline action object. I will now
extract that to add toggle todo action creator, to which I pass the ID of the todo as the argument.

I'm now scrolling up to my action creators and I will add a new one that I call toggle todo. It accepts the
ID as the argument and it returns the action of the type, toggle todo, and this ID.

Let's take a moment to consider how convenient it is to have all the action creators in a single place so
that I can use them from components and tests without worrying about the action's internal structure.

Know that whether you use action creators or not, the data flow is exactly the same, because I just call
the action creator to get the action object and then I call dispatch just like I did before, passing the
action.

35

You might also like