React with Redux

As we know now, React handles the UI layer for presentation of the data to the user. Redux, on the other hand, is the state container which handles the data changes predictably and consistently for the application.

React and Redux form an awesome twosome which make building fast and trendy applications a very easy task, once you understand the full power of the duo.

In this blog, we will understand how React and Redux work together.

Let’s understand the different terminologies involved in this association with the help of an example.

If you don’t know me yet, I am fond of pets, so I will take an example of a simple Pet store application. Let’s call it “Abby”.

Lets define the views for Abby. Keeping it simple, we will have the 2 basic views.

  • List view: List of all the available pets.
    • Each List item included in the complete List view
  • Detail view: Details of the specific selected pet.

Now what is the data which the application deals with. Let’s see,

  • A list of all the pets
  • Details of the currently selected pet

ABBY

The above diagram segregates the data and the view required for our application.

As we discussed earlier, React deals with the view part i.e. defining the UI for the list view and details view. Redux is the state container i.e. the collection of all the data which describes the application.

UNDERSTANDING TERMINOLOGIES WITH EXAMPLES

State

State is a plain JavaScript object which exists in any instance of a class based component and is used to record and react to user events. In simple terms, the state may hold the data and actions or events associated with the class based component.

As function based components do not undergo any changes and are only for display, they do not have any associated state.

In our example, the state comprises of two sets of information –

{

pets : [{name:Buddy, type: pug}, {name: Angel, type: poodle}, {name: Nemo, type: Clown Fish}],

selectedPet : {name:Buddy, type: pug}

}

Action Creators

State is modified by calling Action Creators. Action creators are functions which return Action, a plain JavaScript object comprising of below two elements.

  • Type – The action type, which is defined as a string constant, helps to identify the specific action uniquely. For e.g. an action to fetch all the skill details could have a type of FETCH_SKILLS.
  • Payload – This is the request which is being sent as a part of the action which will result in the change in State. This is the actual data which is being passed.

In the current example, we will define an action creator to get the details of the selected pet. This is in the actions folder

src/actions/index.js

action-creator

Reducers

The reducer is a pure function that returns a piece of the application state. The application can have as many reducers as many pieces of state which comprise the application. The action is sent to all the reducers, based on the action type, the reducer returns the specific piece of application state for the action.

In the pet example, we need two pieces of information, hence we define 2 reducers in the reducers folder.

  • To get the list of pets(to keep the example simple, this returns the json directly.)

src/reducers/reducer_pets.js

pet-reducer

  • To get the selected pet – The reducer here handles the type ‘PET_SELECTED’. The same reducer  can be used to handle different action types by using switch-case statement.

src/reducers/reducer_selected_pet.js

pet-list-reducer

All reducers should be combined to make it available for the data store of the application. This is done using combineReducers function.

src/reducers/index.js

combine-reducer

Store

The Store is the object that holds the action and reducers together. The store has the following responsibilities:

  • Holds application state and allows access to state via getState();
  • Allows state to be updated via dispatch(action);
  • Handles Registering and unregistering of listeners.

An application will have only a single store but can have multiple reducers which are combined and imported as one.

src/index.js

index

Middleware

As the name suggests, middleware is the intermediator between the action and the reducer. Its purpose is to intercept an action that has been dispatched, and modify the action,as required before it reaches the reducer.  We will see this in detail in the next blog where we fetch data using AJAX request and see how middleware helps to format the data as required.

Containers

A Container is a smart React Component which has a direct connection to the state of the application managed by Redux. It is used to bind the component to the store of the application.  In this component, we use the react-redux bridge to connect the data from redux to the view from react.

You can install react-redux to make use of this in your application

npm install --save react-redux

Finally the new state assembled by the reducer, flows from the reducer to the Containers (or components) which re-render themselves to reflect the current state.

For our example, we will pick up the PetList component and see how it binds with the ActionCreator and becomes a container.

We start off with a simple component definition.

List-component

Next we add  the code to make it a Container by importing the related functions to do the binding.

bind

We are making use of this.props, but how does this piece of state become available to this component. Below is the code for mapping and binding the component with the store.

mapping

Now we will understand what each of these functions do.

mapStateToProps –  This function passes the application state to the component. The function takes the application state as its input and returns whatever props we intend to make use in our component. It makes available only the pieces of state which are useful for the component.

In this example, for the PetList component, we need the list of Pets, which is present in the Pets prop which is returned by this function. Then we can use this.props.Pets to refer to the data in our component.

Connect – Another step needed for this is to connect the state to the component which needs the value of the state. In this case the state is connected to PetList component as below.

export default connect(mapStateToProps)(PetList);

mapDispatchToProps – This function passes the action to all the reducers. This is done through the function bindActionCreators which ensures that the action flows to all the reducers through dispatch which acts as a funnel. Whatever this function returns, becomes available as a prop to the container. In this case this.props.choosePet is the action available to use here.

Last piece in this wiring is inclusion of this action in the connect function to make the container aware of the new dispatch method choosePet.

In simple terms, using this connect function, we are making the container PetList aware of the prop data(state) and prop dispatch methods(action), available for use.

export default connect(mapStateToProps, mapDispatchToProps)(PetList);

You can read more about connect here.

 

You can check the code for the complete Abby application here.

STATE FLOW DIAGRAM

As a quick recap, below diagram shows the flow of state between different elements.

react-redux-flow-state

CONCLUSION

This blog introduces all the main concepts and terminologies to work with React and Redux using a simple Pet Store application.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s