Manage Your State With Redux in Your React Application

Oğulcan Davran
The Startup
Published in
7 min readOct 26, 2020

--

Best Buddies

What is State?

I want to start off by explaining “what is state?” in programming. It is like a combination of conditions of each stored data related to your application. Your state is composed of full of little information, together they make your application a whole and give your application incredible abilities like being dynamic. Think as each information has its own different phases and you can change how your application behaves in each different phases. Since each information as a part of your state can change/evolve during the runtime, state can be thought as dynamic data collection.

State in programming is similar to state of elements in science(gas, liquid). It stores its phase/condition and in programming, we can change how our application looks like in its present condition.

Do you need Redux?

Enough with state, where does Redux come into play? In its simple term, Redux is a predictable state container for JavaScript Apps. It helps you manage your application state in a consistent and predictable way.

Before we dive into the details of Redux, there is a decision to make based on the needs of your application. Does your application really need state management in Redux level? Can you manage your state without Redux? This is solely a decision you need to make with consideration of your application.

Redux official documentation gives pretty good explanation whether you need Redux.

In general, use Redux when you have reasonable amounts of data changing over time, you need a single source of truth, and you find that approaches like keeping everything in a top-level React component’s state are no longer sufficient.

Redux solves many problems but it comes with difficulties. In the end, it really depends on your application and its size. If you are not sure you need it, you can always add Redux to your application later. During this decision, it is important to know the benefits of Redux, what Redux provides to your application.

With Redux, you can simply;

⦁ Hold your entire app’s state in one single object(Store)

⦁ Maintain data flow

⦁ Debug and test easily

Redux performs best when your application gets bigger. It gives your application the ability to manage your application data with single source of truth. You can give your components only the data that they need, nothing more which makes your application easy to maintain.

I think that the strong side of Redux is you have a standard way of maintaining data. You can add new features without touching the business logic of your application and focus on your development because you know you can give even the deepest level of component the data from the store not by building another logic but by exploiting Redux’s strongest side — data flow.

Redux architecture revolves around a strict unidirectional data flow.

This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand. It also encourages data normalization, so that you don’t end up with multiple, independent copies of the same data that are unaware of one another.

Redux Terminology

Redux is a library hard to understand the concepts and terminology. You may not have a clue so far what Redux is actually doing or how it is doing. I will do my best to simplify terms. After some understanding, it will make a great sense and you will be able to tell whether you need Redux in your application and integrate Redux with the knowledge of what you are really doing instead of writing memorized code.

Let’s start with the principles of Redux. Here is three principles of Redux;

Single source of truthThe state of your whole application is stored in an object tree within a single store.

State is read-onlyThe only way to change the state is to emit an action, an object describing what happened.

Changes are made with pure functionsTo specify how the state tree is transformed by actions, you write pure reducers.

These principles are what gives Redux its capabilities. Redux is build upon them and these are the reason Redux is great at big complex projects.

In terms of terminology, there are few terms that you need to understand to write Redux. It can be overwhelming at first, if you are not familiar to Flux, but I promise it gets so much easier when you have the gotcha moment

Redux Terminology

Actions

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().

⦁ Actions are objects

⦁ They must have a type property which defines the action performed

⦁ They are the information that leads to the change of store

⦁ It simply tells us what happened in application

⦁ Type property is generally a string constant

const CLICKED = “CLICKED” // type property// Actionimport { CLICKED } from ‘../actionTypes’ // importing type variable{  type: CLICKED,  payload: ‘button clicked’}

The reason why type property is uppercased is that it is intended to show that they are meant to be constants. To save it in a constant variable is good practice, preventing writing errors and keeping them in a separate file is also common practice in organizing your code.

Note: We send actions to the store with dispatch() function in Redux, but in React-Redux integration we use connect() function to do that. Since this article is focused on React-Redux integration, I will suggest that if you want to know more about dispatch(), you can check online sources.

Action Creators

They are the functions that produce actions.

⦁ They are functions

⦁ They return action

function buttonClickedActionCreator (text) {  return { 
type: CLICKED,
payload: text
}
}

Reducer

Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.

⦁ Reducers are pure functions

⦁ Reducers are the only way to change state

⦁ Reducers take the action and previous state then they return new state

⦁ Reducers’ arguments should never be modified

⦁ Reducers should never handle API calls

⦁ Reducers always should be pure functions

Reducers take previous state and the action as parameters. It checks the type of the action and produces new state and updates store with the payload of the action.

Important point here is that you should not mutate arguments of the reducer. What you should do is that you should create a new version of the previous state and make changes to new state then return the new state. This new state will be updated by the action payload.

There are ways to handle immutability. For example, you should not use methods that mutate array (push, shift, unshift…) if you are dealing with arrays. You can use spread operator and other methods that are available. I am leaving some of them below.

Do not mutate arrays && objects

Let’s write one simple reducer to see what it looks like.

import { CLICKED } from ‘../actionTypes’ // importing type variableconst initalState = {isClicked : false} // initial statefunction buttonClickedReducer(state = initialState, action) {  switch (action.type) {    case CLICKED:      return Object.assign({}, state, { isClicked: action.filter })    default: return state 
}
}

We are importing the type variable, because we wanted to keep it as a constant variable in a separate folder. This is optional.

We are specifying the default state since Redux will call reducer with an undefined for the first time. So, we are returning state of the application as a start.

In the function, first argument is the old state and the second one is the action object with type and payload properties.

In switch statement, we are checking type property to see if it is the right action, if not, we are returning previous state nothing else. If it is the right type, we are creating a new state and returning the new state. But we are not mutating old state directly, we are making a copy of it and change the copy.

Redux action, action creator, reducer all make the Redux cycle. They are all part of the cycle.

Visualization will help you understand better.

Redux Cycle

⦁ Store is the one that holds application state

⦁ It updates UI

⦁ UI triggers action

⦁ Action gets dispatched

⦁ Reducer provides new state

⦁ Reducer updates store

If you are unsure whether you understand all cycle, what action is, what reducer does, you definitely need to look for more resources especially official documentation. This cycle and terminology is essential to know if you are going to write Redux. Here some points that need to be highlighted;

. What is store, action, action creator and reducer?

⦁ How Redux handle state management?

⦁ Do I need Redux in an application?

⦁ What are pure functions?

. Why is it important that reducers are pure and we do not modify arguments?

⦁ Why do we define initial state?

In the next article, I will try to make a Github Repo for the boilerplate in integration of Redux with React application. Follow up for more Redux and React!!!

--

--