user

Development, April 4th, 2017

How To Use Redux To Make Your React Project Easier

How To Use Redux To Make Your React Project Easier

Joining Apptension, a software development company, I was a junior frontend developer. I had some initial experience with React, so one of my first projects was based on this library. In this post I will explain how I used Redux to make them even easier.

It is becoming, actually, one of the most commonly used libraries, according to Stack Overflow Survey 2017. In the category of frameworks, libraries, and other technologies, it is now the fourth one, after Node.js, AngularJS, and .NET Core.

react library survey

Source: Stack Overflow

 

React is great for simple projects

My first React project was a simple restaurant’s website. It featured some basic contact info and a google map embedded.

Having analyzed the project, we reached the conclusion that we are able to achieve the desired effect using standard JavaScript events as well as transmitting props, which React offers.

But then, the client submitted changes which were difficult to implement based on it. As we’d had the main structure in place, we needed to continue development with regular events.

 

Use Flux or Redux for more complex implementations

To avoid situations like the one described above, it is best to use the Flux architecture. It makes React components much more independent from each other.

One of the most popular implementations of this structure is Redux.

We’ve decided to use it in our next project, that was also based on React. It helped us with assuring the proper data flow, and we were able to avoid many problems with transmitting data to the particular components.

As you can see, Redux can improve developing projects based on React, making them much more flexible to future changes.

Before I introduce the components of Redux one by one let’s quickly recap the general concept behind React and Flux to see how Redux differs from it.

 

React, Flux, and Redux: What Are They?

If you are already familiar with how React works, what is Flux and how Redux differs from it, you can easily skip this part and go right to the Redux-oriented part of this article.

But if you are still a little bit confused with all of this (I definitely was when I first started exploring these terms), I will explain the basic ideas behind React and Flux:

 

What React is, and what it isn’t

First of all, React is not a framework itself. That’s why you can’t compare it to Angular, for example. It is only a view layer, a library that stores the so called “components”, allowing to keep their own internal state in memory.

In the words of Facebook developers:

“React is a declarative, efficient, and flexible JavaScript library for building user interfaces.”

For simple websites it is really great and easy to use, but when the project gets more complex, dependencies between components are getting hard to manage.

 

The concept of Flux

That’s where Flux comes in handy. But again, the concept of Flux may be as confusing as React’s definition. Why? Because Flux is not actually the framework, either:

“Flux is more of a pattern than a framework”

It is a concept of an architecture, that adds an unidirectional data flow to React’s components:

flux diagram

Source: Facebook’s GitHub

 

What about Redux?

Ok, so let’s get to the main part – what Redux really is? It is one of the most common implementation of Flux.

Shortly, it is a state container for JavaScript apps. These are the main advantages of using it:

“It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.”

It may be used with other libraries to create a structural view of an application, as well as with other frameworks with implemented state of an application.

At the same time, it doesn’t fully cover the theoretical assumptions of Flux, though it is perfect for tasks, for which this architecture should work.

It helps to keep your code in order, managing the data flow between components.

 

The four-blocks concept of Redux

Redux can be easily explained with a four-blocks example:

redux concept

Let’s discuss them one by one:

 

1. Action

Actions can be identified on any website. It may be downloading the data by the browser, or clicking an element by the user. Redux defines these as actions.

All interactions have their own type of action, which is their unique identifier, and their data (e.g. an object, array, flag, or even text).

See the example of such actions below:

export function submit( email, locale ) {
  return {
    type: SUBMIT,
    payload: { email, locale },
  };
}

This exemplary action has its unique type, which is defined above. Then other parameters are being passed, and moved further to the reducer when the action is called.

 

2. Reducer

Reducer is the part of an application, that takes care of inputting changes to the application’s state, based on the type of action.

You need to remember, though, that the reducers are not meant for sending requests to the servers.

The structure of a reducer is very simple:

const initialState {
  isLoading: false,
  isSent: false
};

function simpleReducer(state = initialState, action) {
  switch (action.type) {
    case SUBMIT:
      return Object.assign({}, state, {
        isLoading: true
      });
    case SUBMIT_SUCCESS:
      return Object.assign({}, state, {
        isLoading: false,
        isSent: true
      });
    default:
      return state;
  }
}

As you can see in the example above, some default data should be created at the beginning of every reducer. This is the initial object of the application’s state.

Then, depending on the type of action, it will be sent to the module and processed. After that, a new object of application’s state is created and returned.

 

3. Store and View

As you have already seen, the pictured application’s state (store) is a one big object, modified by the reducer, depending on the type of an action.

Unlike the first two elements, store does nothing except well, you may have guessed it storing the data.

Then the object is uploaded to thea particular views (components) of an application. Depending on the requirements for passing data to the component, only a given values are being passed, not the whole object of application’s state.

Next, they are being displayed or processed, in accordance with requirements.

 

Simple implementation of unit tests

The process shown in the diagram above is not too complicated, as Redux is a quite simple implementation of Flux.

Thanks to its simplicity, it is very easy to learn and implement in many projects that rely on React.

What I haven’t mentioned yet, is the ease of testing the Redux elements. Since every big element is divided into smaller modules, there is no problem to write unit tests for them. They are necessary for ensuring a proper implementation of the project, so that we don’t need to check everything manually.

Studies, conducted by companies like Microsoft and IBM, shown that writing unit tests leaves up to 15-35% more time for development, reducing the number of bugs by 40-90%.

It is a big advantage, and you can easily test an application that uses Redux.

 

Conclusion

Building websites you need to always assume that the project may need to scale up. That’s why it’s better to use tools and technologies that will let you do it effortlessly, without the need of rewriting the code.

For me, switching to using a combo of React and Redux was a good choice.

These two libraries helped me with building and testing projects, and I can recommend using them to you as well.

 

Do you have any questions? Please, leave them in the comments below. I’ll be happy to help you.

P P