A Deep Dive into Redux: Part-1

Arpit Jain
Software Development Company West Agile Labs
5 min readJul 23, 2019

Since I started working with ReactJS, I have only used it to create simple react apps or reusable components. I have used ReactJS only to create a react application and have never tried to integrate it with something more.

A lot of my friends and colleagues always asked me to create-react-app by using Redux. And my answer was always something like: “I haven’t worked with redux yet”

Recently I started my job with StackAvenue Technologies and here I am working on a product DailyPloy: “Task Management System”. So In this project, I have started using Redux.

So, here is an article about Redux, how it works, how it should be used to React and all it’s basic methods.

What is Redux?

Redux is used mostly for application state management. To summarize it, Redux maintains the state of an entire application in a single immutable state tree (object), which can’t be changed directly. When something changes, a new object is created (using actions and reducers). We’ll go over the core concepts in detail below.

How Is It Different from MVC And Flux?

To give some perspective, let’s take the classic model-view-controller (MVC) pattern since most developers are familiar with it. In MVC architecture, there is a clear separation between data (model), presentation (view) and logic (controller). There is one issue with this, especially in large-scale applications: The flow of data is bidirectional. This means that one change (a user input or API response) can affect the state of an application in many places in the code — for example, two-way data binding. That can be hard to maintain and debug.

Flux is very similar to Redux. The main difference is that Flux has multiple stores that change the state of the application, and it broadcasts these changes as events. Components can subscribe to these events to sync with the current state. Redux doesn’t have a dispatcher, which in Flux is used to broadcast payloads to registered callbacks. Another difference in Flux is that many varieties are available, and that creates some confusion and inconsistency.

Benefits of Redux

Many people asking “Why would I need to use Redux?”. That's a great question. There are a few benefits of using Redux:

1. Predictability of outcome

There is always one source of truth, the store, with no confusion about how to sync the current state with actions and other parts of the application.

2. Maintainability

Having a predictable outcome and strict structure makes the code easier to maintain.

3. Organization

Redux is stricter about how code should be organized, which makes the code more consistent and easier for a team to work with.

4. Server Rendering

This is very useful, especially for the initial render, making for better user experience or search engine optimization. Just pass the store created on the server to the client-side.

5. Developer Tools

Developers can track everything going on in the app in real-time, from actions to state changes.

6. Community and Eco System

This is a huge plus whenever you’re learning or using any library or framework. Having a community behind redux makes it even more appealing to use.

7. Ease Of Testing

The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is mostly functions that are just that: small, pure and isolated.

Where Can Redux Be Used?

Most developers associate Redux with React, but it can be used with any other view library. For instance, you can use Redux with AngularJS, Vue.js, Polymer, Ember, Backbone.js, and Meteor. Redux plus React, though, is still the most common combination.

One of the reasons Redux is awesome is its ecosystem. So many articles, tutorials, middleware, tools, and boilerplates are available. Personally, I use David Zukowski’s boilerplate because it has everything one needs to build a JavaScript application, with React, Redux and React Router. A word of caution: Try not to use boilerplates and starter kits when learning new frameworks such as React and Redux. It will make it even more confusing because you won’t understand how everything works together. Learn it first and build a very simple app, ideally as a side project, and then use boilerplates for production apps to save time.

Data Flow of Redux?

Redux concepts might sound complicated or fancy, but they’re simple. The Redux library is only 2 KB. Redux has three building parts: actions, store, and reducers.

Redux Flow Diagram
Reference by Maximilian Schwarzmüller

Actions

Actions are events. Actions send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The store gets information only from actions. Internal actions are simple JavaScript objects that have a type property (usually constant), describing the type of action and Payload of information being sent to the store.

{
type: LOGIN_FORM_SUBMIT,
payload: {username: ‘alex’, password: ‘123456’}
}

Actions are created with action creators. That sounds obvious, I know. They are just functions that return actions.

function authUser(form) {
return {
type: LOGIN_FORM_SUBMIT,
payload: form
}
}

Calling actions anywhere in the app, then, is very easy. Use the dispatch method, like so:

dispatch(authUser(form));

REDUCERS

Reducers based on the array reduce method, where it accepts a callback (reducer) and lets you get a single value out of multiple values, sums of integers, or an accumulation of streams of values. In Redux, reducers are functions (pure) that take the current state of the application and an action and then return a new state. Understanding how reducers work is important because they perform most of the work. Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

function handleAuth(state, action) {
return _.assign({}, state, {
auth: action.payload
});
}

For more complex apps, using the combineReducers() the utility provided by Redux is possible (indeed, recommended). It combines all of the reducers in the app into a single index reducer. Every reducer is responsible for its own part of the app’s state, and the state parameter is different for every reducer. The combineReducers()utility makes the file structure much easier to maintain.

If an object (state) changes only some values, Redux creates a new object, the values that didn’t change will refer to the old object and only new values will be created. That’s great for performance. To make it even more efficient you can add Immutable.js.

const rootReducer = combineReducers({
handleAuth: handleAuth,
editProfile: editProfile,
changePassword: changePassword
});

STORE

The store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers. That makes Redux very simple and predictable.

import { createStore } from ‘redux’;
let store = createStore(rootReducer);
let authInfo = {username: ‘alex’, password: ‘123456’};
store.dispatch(authUser(authInfo));

Redux has a few other features and concepts that perhaps I can cover in another post. Things like asynchronous call and action processing, middleware for logging and error handling.

If you like this article, please recommend it to help others find it!

--

--