Redux - Reducers


If you plan to use Redux as a state management tool, you'll have to deal with Flux concepts like reducers and actions. In this article, we will discuss what they are and how to better implement them for your React apps.

What is State?

The state is a type of object that specifies characteristics of your program that can change over time. You should make your state the bare minimum of data required to explain the application's current state. If Redux manages an application's state, state updates are handled by a reducer that processes actions, as we'll see below. For example, our chat application could be in the following state:

       
    {
        userId: "user-2022",
        username: "Great",
        messages: [
        {
            user: "Great",
            message: "Hi",
        },
        {
            user: "Hannah",
            message: "Hello there!",
        },
        ],
    };
 

What are Actions?

Actions are a simple JavaScript object that holds data. Actions have a type field that specifies the type of action to take, and all other fields contain data or information. Actions are the sole way for the Redux store to be updated with new information; they provide the payload for changes to an application store. Actions tell Redux what kind of action to perform, like the following:


    const action = {
        type: "ADD_TO_CART",
        payload: {
          product: "doughnut",
          quantity: 6,
        },
      };      
   

The code above is a typical payload value that contains the data that a user sends and is used to change the application's state. As you can see from the example above, the action object contains the type of action and a payload object required for this action to be completed. Reducers update the store based on the action.type value; here, ADD_TO_CART.

What is a Reducer?

A reducer is a pure function in Redux that accepts an action and the application's previous state and returns the new state. The action specifies what occurred, and the reducer's role is to return the updated state as a result of that action. Pure functions have no side effects and will produce identical outcomes if the same arguments are handed in.An example of a pure function is as follows:


    const add = (a, b) => a + b;

    add(3, 6);
   

The code above returns a value based on the inputs; for example, if you pass 3 and 6, you'll always get 9. As long as the inputs are the same, nothing else influences the result; this is an example of a pure function.

A reducer function that takes in a state and action is shown below:


    const initialState = {};
    const cartReducer = (state = initialState, action) => {
      // Do something here
    };
   

Each time an action is dispatched, the state is updated in terms of its current value and the incoming values in the action.