Redux for State Management in React

Redux will be used to handle a React app's state in this lesson. Unlike top-level components that include both logic and state, Redux allows you to maintain and manage the state of a complete application in a single object.
Table of Contents

Need Help? The Cybernative Team Is Here To Answer Your Queries.

Table of Contents

Complex user interfaces may be readily created by developers with React. React components require data access to enhance UI interaction.


The information may either be defined inside the application or be a response from an API endpoint. An interaction, such a button click or text entered into an input box, will cause this data to be changed.


A state is an object that contains the data inside a React component. React updates the screen with the updated data whenever the state of the component changes, allowing the user interfaces to be shown.


The state may be required by several components in a React application. Because of this, it must be handled well. Storing and updating data in an application is necessary for effective state management.

An Overview of Redux

“Actions” are events that are used in the Redux pattern and library to manage and update the state of an application. Essentially, it acts as a single repository for all application-wide state, with restrictions limiting state updates to known patterns.


Keeping track of, updating, and maintaining the state of your application is made easier using Redux’s central store. Hence, none of our components may have states. Various parts of your application will be able to access the state as it will be centrally located.


Redux solves what kind of problem?

Here are some categories into which a simple React app may be divided:


State: The current condition of the app

View: The UI of the app

Actions: A function that updates the state when an event occurs in your app (generally referred to as Event handlers).


A state can be possessed by any part of an application. If several components want access to the same data, though, then it becomes problematic. We “lift the state up” in order to resolve this matter. State can be moved from a child component to its parent (top-level) component by a procedure known as “lifting state up.” Shared state across numerous child components may be readily achieved using this method.


But “lifting state up” has drawbacks as well:

That may make your code more complex: If you raise the state, your components may include a significant amount of boilerplate code. Prop-drilling occurs because the parent component has to transmit the state to the child components. Furthermore, in the parent component, the state is updated.

Performance may be impacted by it: A higher number of components will re-render when the state is changed when the state is lifted up. Particularly on mobile devices, this may have an impact on performance.


More states will be managed by our code in a large-scale single-page application. This condition may comprise locally generated data that hasn’t yet been saved to the server, cached data, and server answers. You won’t be able to manage the state updates’ when, why, or how at that point. preventing the reproduction of errors or the addition of additional functionality.


        Understanding the Terminologies in Redux

        The terminologies to familiarise yourself with are as follows:


        1. Actions

        That the state is read-only is Redux’s second rule. Only by submitting an action can you make changes to the state tree. This prevents any direct writing to the state by the views and network callbacks. They convey an intention to change the status instead. That is, the only advised method of altering the application state is to take action. 


        In the application, an action describes what has happened. Holding the data needed for the store to change the state, it is a JavaScript object that is sent as a parameter to the store. Within each application, each action is different. As an illustration, the following activities are all that are required in a counter app:


        • increased the count
        • decreased the count

        In a todo app, you may have the following actions:


        • Added todo item
        • Deleted todo item
        • Complete todo item
        • Filter todos, etc.

        In Redux, the components are not aware of the precise way in which the state is modified since the state and components are kept apart. They just have one concern, which is that they must reply.


        You may indicate the event that occurred in your component using the action object type attribute. In order to assist update the store’s state, the event handler function will, in effect, send out an action whenever an event takes place.


        Payload is another characteristic of the action object. The payload contains any newly acquired information about the incident. For instance, the new to-do item and the ID may be included in the payload when I dispatch an operation of type “addedTodo”. 


        Below are examples of action objects:

        //action 1

        const addTodoAction = {

          type: ‘todos/todoAdded’, //what happened

          payload: {todoID, newTodo} //data

        }

        //action 2

        const getOrder = {

        type: ‘orders/getOrderStatus’, //what happened

        payload: {orderId, userID} //data

        }


        2. Action Creators

        Because the action creators include functionality that can be used in many application instances, you may supply certain parameters that can be accessible in the action objects. The action creators are functions that return action objects.


        Below are examples of action creators:


        //example 1

        function addTodo(todo){

        //return action object

        return {

          type: ‘todos/addTodo’,

          payload: todo // what happened

            }

        }

        //example 2

        function getOrders(orderID, userID){

        //return action object

          return {

               type: ‘orders/getOrderStatus’,

               payload: {orderId, userID} //what happened

           }

        }


        4. Reducers

        The updated state is returned by a reducer, which is a pure function that takes as inputs the current state and an action. The reason it’s called a reducer is since the Redux reducer gradually condenses a sequence of operations into a single state, much to the Array.reduce() function.


        Pure functions are ideal for the reducer. When two inputs are given the same result, a function is said to be pure. None of the other functions’ states or the global state are altered in any way.


        In other words, this means:


          • Modifying the current state is prohibited for a reducer function. It is necessary for them to duplicate the existing state and then update the duplicated information.
          • By reading from a database, a reducer function shouldn’t update the state.
          • Avoid calling any third-party APIs from a reducer function.

          Below is the syntax of a reducer function:


          const myReducer = (state, action) => newState


          The reduction function’s reasoning goes like this:



          We do an action check in the function’s action.type attribute.


          The action will create a copy of the state and update it with the new value if the kind of action is one you have defined the action.payload

          Reverting to the current state will occur if the action.type does not match anything you have defined. 


          Below is an example of a todoReducer function:


          const intialTodo = [{id:1, todo:””}]

          const todoReducer = (state = initialTodo, action)=>{

          if(action.type === “todos/AddedTodo”){

            return […state, todo: action.payload]

          }else{

          return state

           }

          Wrapping Up

          You used Redux to control a React Todo app’s state in this guide. Proceed to study the Redux Toolkit’s state management techniques. Redux Toolkit accelerates development by making it simpler to construct quality Redux apps. To help you track down the where, when, and why behind changes to the state of your application, become familiar with Redux DevTools.


          Related Posts:

              For more updates and information visit CyberNativeTech and follow us on LinkedIN.

              Need Help? The Cybernative Team Is Here To Answer Your Queries.