Redux: Reasons to use and how to use it in ReactJs (with clear examples)

Due to the number of tools and libraries out there for web development, it might not be the wisest thing to jump on every new one without really understanding its benefits or why you should use it. Redux is of no exception. This development tool is certainly not new, yet it is quite popular in the community of developers. That is to say, the tool is so prominent that every developer should at least know about it, if not use it in React.

So, if you have no idea what Redux is and you want to know why you should use it, this article is for you. Even if you know what this thing is but still wonder if you are making a wise choice by using it in your app, this article is also for you. In this article, we will consider some reasons why you should use this method by discussing its benefits. Also, we would like to give you a small tutorial on how to use it in ReactJS, with a clear example obviously

redux

But first, let’s go through some definition.

What is Redux?

Redux is a predictable state container for JavaScript applications. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. To give it an easier way to explain, it’s just like a state management tool. With Redux, the state of your application is kept in a store, and each component can access any state that it needs from this store.

Redux, though mostly used together with React, it can be used with any other JavaScript framework or library. It is lightweight at 2KB (including dependencies), so you don’t have to worry about it making your application’s asset size bigger. This module is also exceptionally good at the separation of concerns, with a clear break between the Store that holds the data. Moreover, the code that changes the store, and the Actions that the components call to ask for a change.

Some reasons to use Redux for your eCommerce website

#1. The sole yet effective application state

One sole yet effective application state with Redux
One sole yet effective application state

Together with this module, there’s one general state in the store, and each component has access to the state. When using it with React, states will no longer need to be lifted up. Thus, it makes it easier for you to trace which action causes any change. The general component, meanwhile, does not need to provide any method for its children components to share data among themselves. Everything is handled by this tool. As a result, this greatly simplifies the app and makes it easier to maintain.

#2. Redux makes the state predictable

In Redux, the state is always predictable. If the same state and action are passed to a reducer, the same result is always produced because reducers are pure functions. The state is also immutable and is never changed. As a result, this makes it possible to implement arduous tasks like infinite undo and redo. It is also possible to implement time travel — that is, the ability to move back and forth among the previous states and view the results in real-time.

#3. Maintainable and unbuggable

Maintainable and unbuggable using Redux
Maintainable and unbuggable using Redux

Redux is strict about how code should be organized, which makes it easier for someone with knowledge of this module to understand the structure of any application. This generally makes it easier to maintain. Also, this module makes it easy to debug an application. By logging actions and state, it is easy to understand coding errors, network errors, and other forms of bugs that might come up during production.

#4. Ease of testing and state persistence

It is easy to test Redux apps since functions used to change the state of pure functions, UI and data management are separated. Moreover, you can persist some of the app’s state to local storage and restore it after a refresh. This can be really nifty. No worries of, from where the data is coming as stores are certainly the single source of truth. Another way of looking at this – it helps you manage the data you display and how you respond to user actions.

#5. Server-side rendering

Server-side rendering on Redux
Server-side rendering

Redux can also be used for server-side rendering. With it, you can handle the initial render of the app by sending the state of an app to the server along with its response to the server request. The required components are then rendered in HTML and sent to the clients. All in all, when you need to manage a complex state in a JavaScript application, this module can be very powerful.

How to use Redux in ReactJS (with the clear example – a to-do list)

The way Redux works is simple. There is a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another. There are also three building parts: actions, store, and reducers. So, how can we use Redux in ReactJS? The below part of this article will help you. That is to say, let’s get into the usage, with an example of creating a to-do list.

Entry point (index.js)

Action creators (action/index.js)

Simply put, actions are events. They are the only way you can send data from your application to your Redux store. What’s more, the data can be from user interactions, API calls, or even form submissions. Actions are also created via an action creator. The following code is the example of creating actions for your to-do list.

let nextTodoId = 0
export const addTodo = text => ({
type: 'ADD_TODO',
id: nextTodoId++,
text
})

export const setVisibilityFilter = filter => ({
type: 'SET_VISIBILITY_FILTER',
filter
})

export const toggleTodo = id => ({
type: 'TOGGLE_TODO',
id
})

export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}

Reducers in Redux

They are pure functions that take the current state of an application, perform an action, and return a new state. These states are stored as objects, and they also specify how the state of an application changes in response to an action sent to the store. This is certainly based on the reduced function in JavaScript, where a single value is calculated from multiple values after a callback function has been carried out.

const LoginComponent = (state = initialState, action) => {
    switch (action.type) {

      // This reducer handles any action with type "LOGIN"
      case "LOGIN":
          return state.map(user => {
              if (user.username !== action.username) {
                  return user;
              }

              if (user.password == action.password) {
                  return {
                      ...user,
                      login_status: "LOGGED IN"
                  }
              }
          });
default:
          return state;
      } 
};

Store in Redux


Let’s create a store for our login app:

const store = createStore(LoginComponent);

The store holds the application state. There is only one store in any of the module’s application. You can access the state stored, update the state, and register or unregister listeners via helper methods. Actions performed on the state always return a new state. Thus, the state is very easy and predictable.

Now, let’s see how Redux can improve the component:

class App extends React.Component {
    render() {
        return (
            <div>
                <Status user={this.props.user.name}/>
                <Login login={this.props.setLoginStatus}/>
            </div>
        )
    }
}

Presentational components

components/Todo.js

components/TodoList.js

components/Link.js

components/Footer.js

components/App.js

Container components

containers/VisibleTodoList.js

containers/FilterLink.js

Other components (containers/AddTodo.js)

Final words

That should be it! Here are the reasons why we should use Redux in ReactJS, with the perfect example of creating a to-do list. While the module has its benefits, that does not mean you should go about adding this tool in all of your apps. Your application, however, might still work well without it. Hopefully, after reading this article, it will help you on your own journey with this module whatsoever.

We – ArrowHiTech is proud to be one of the most well-established outsourcing companies all around the world. That is to say, with over 12 years of experience, we can provide the best mobile app development services for your business. Also, if you want to go through our showcase, you should visit our product page here: MageSolution or our portfolio: ArrowHiTech portfolio.

ArrowHiTech services

If you have any questions, don’t hesitate to contact us via email support@arrowhitech.com or our phone number +84 243 7955 813. We would love to hear every feedback from you guys.

Related News

React component: A complete overview of its types and differences

Kotlin vs React Native: The complete comparison you need to know about

Tags

Share