Redux: The State Management Library That Will Change Your React Development

Redux: The State Management Library That Will Change Your React Development

Learn the Core Principles of Redux for State Management in JavaScript Applications

ยท

8 min read

We all heard about Redux when learning React. Oh yeah, I even saw some companies mention it in their job description. (High possibilities in the ReactJS & Front End Developer job description).

Because when dealing with complex components, redux can help to simplify state management. So many companies looking for a developer who also knows Redux.

Redux will be irritating and frustrating if you learn it in the wrong way. But you will love it when you understand the core concept of redux.

So, before we start project-based learning, let's take a look at some of its core principles in this post.


Who's this article for, If you are struggling to understand redux basic concepts it's for you...


So What is Redux?

So redux, redux, redux you have been hearing this all the time especially when you are starting the React journey. So what is exactly the Redux?

Redux is a state management library. Which manages the state of your Javascript Application.

Instead of thinking state as a complex with what you write in React. Think of the state as some form of data.

Here redux provides a structured way to communicate and manage data with the 'store'.

Just know there is a place called the store where you can manage the data for your entire application in one place.

What were redux docs say about redux?

Redux is a pattern and library for managing and updating application state, using events called "actions".

Let me try to be more clear...

Think of Redux as a shared document for an application.

It helps different parts of the application stay in sync & work together towards a common goal.

It's like everyone working together to build a house using a shared blueprint and updating the progress in a shared document.

Redux makes the shared document or shared blueprint available for the entire application or an entire team of builders.

Redux is Predictable

In redux, the state is read-only. (A state is an object that holds information or data that is subject to change).

That means you can only read or see the data being displayed in the application.

You cannot change the state directly in redux, this is what makes redux predictable.

You need to dispatch (send) an action (instructions) that tells what changes you want to make.

The reducer function will receive the actions. (Function who listens to the instructions that were sent)

Its sole purpose is to accept the action and the current state. Then, it returns an instance of the newly updated state.

Note -

The reducer function does not change any part of the state. It rather returns the instance of the newly updated state.

So you can see a clear history of changes to the state that you made in your application using redux dev tools.

According to the creator of Redux

"Actions can be recorded and replayed later, so this makes state management predictable. With the same actions in the same order, you're going to end up in the same state".

If you don't understand what is action and dispatch it's okay we will talk about them in more detail in this post below.

Why should you use Redux?

Explaining how application is with redux and without redux

Well okay then, it's made easier to work with the state. Is it the only advantage redux can give us?

No... There are some other advantages. I will explain some of those below...

Centralized Store Management.

So you are passing the prop from the parent component at level 1 to the child component at level 4.

While passing the prop you had to go through the child component at level2 & 3.

But with Redux you don't have to do that, because you can maintain the state of your app in a single store.

So you can easily pass it down from the store to any part of your app.

Predictable State

The change in the state only happens when you create an action and pass it to redux.

This makes it easier to understand how your application data will change.

Performance

You reduced the number of prop drilling with centralized state management.

And also, you decreased the state update because in redux we have to create actions to change the state.

These help your Javascript application to improve performance.

Easier Debugging

Redux dev tools is an extension for browsers and there is also an npm package for locating and fixing your errors easier. It will save more time and effort.

State in redux is predictable, so this also makes it easier to debug your code.

Core Principles of Redux

As we discussed before, redux allows you to maintain a centralized store and helps to manage your entire app.

The principles listed below are important. this helps you understand how redux works.

  • Store

  • Actions

  • Dispatch

  • Reducers.

Before we start an in-depth view, you should remember this,

Store - It is a place where you store a state and pass through your entire application.

Action - Action is an informer who holds the instruction about how to modify your state.

Dispatch - Dispatch is the one sent action to the reducer function

Reducer - A reducer who receives the current state value and action (instruction to change state) and as per predefined instruction it changes then returns the instance of the state.

Store

Wooden box used to explain the store in react redux

Think of the store as a wooden box that stores different kinds of fruits. The wooden box contains carrots, Mangos, oranges, Apples, and so on.

Like that store is a container that holds different types of data types.

It can store strings, numbers, arrays, objects, and even functions.

It is considered and maintained as a single source of truth, which means any components or part of your application can assess the store. So you can retrieve and update your application.

Actions

As we discussed before, a state in the redux is read-only.

It restricts any network calls, API calls, and form submissions to update directly. If anyone wants to change the state of the application, it will be done by action.

Action is plain Javascript objects that have type and payload.

Type - It indicates the type of action to do.

Payload - It is an object that contains information that will be used to change the state.

And here is a basic example of action.

{
  type: 'ADD_TODO',
  payload: {
    id: 1,
    text: 'SOME TODO TASK',
    completed: false
  }
}

To create action we need action creators. Action creators are nothing more than functions, that create and return action objects.

A basic example of an action creator.

// Action creator is a function 
// that creates action objects
const addToDo = (itemText) => {
  return {
    type: 'ADD_TODO',
    payload: {
      text: itemText,
      completed: false
    }
  };
};

// Dispatching the action
store.dispatch(addToDo("SOME TODO TASK"));

Dispatch

Dispatch is a function that is provided by the redux store. Dispatch allows you to send the actions to the reducer to update the state of the application.

For example, think of dispatch as a postman or (a person who delivers a letter door to door in a small village or area. Note, I am not talking about the Postman API tool).

Dispatch is like a postman who delivers letters to different houses on the street, ensuring that each letter reaches the right address.

Like the postman, dispatch delivers actions to various reducers in the redux store.

In this example

Dispatch represent postman

Houses represent reducers

The street represents the redux store

Reducers

If you don't understand the basic concepts of state, action, and dispatch, it can be challenging to understand the reducer.

So go through the concept if you need help understanding.

In redux, reducers are pure functions that take action and state as an argument and return the new state.

There can be more than one reducer that takes care of different parts of your application. It depends on how big your application is.

For example, there can be a reducer handling a post and another reducer handling a user in a blog application.

When dispatch sends an action (information), it triggers the execution of all the reducers. Each reducer checks the type of action using a switch statement.

When the action type matches with the switch statement, the reducer changes the state and produces a new updated version of it.

Here basic code example for Reducer in redux

const initialState = {
  count: 0
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        count: state.count + 1
      };
    case "DECREMENT":
      return {
        ...state,
        count: state.count - 1
      };
    default:
      return state;
  }
}

Every reducer needs to have a "default" case in its switch statement.

This is to make sure that if the reducer doesn't recognize the action type being passed, it doesn't break and returns the current state instead.

It's also important to have the right reducers in place to handle the specific types of actions that will be sent.

A perfect analogy to explain a reducer would be a paint mixer.

Similar to a paint mixer that takes in different colors of paint, mix them, and produces a new color, a reducer takes in the current state of an application and an action combines them and generates a new state.

That's all for the core principles...

If you know these basic concepts you will be comfortable when learning redux.

If you have any doubts about the above concepts, comment here, and don't forget to follow me for more content.

Hope you have a great day... ๐Ÿ˜Š

ย