I Love ReactJS

Essential skills for React developers: master the basics and applications of useReducer

in React, the management of component state is very important. Typically, we can use useState to manage component state. However, using useState can become very tedious if the state becomes more and more complex. At this point, we can consider using useReducer to manage the state.

you might ask, why not use Redux? It is true that Redux is an excellent and popular state management tool, but there are some scenarios where Redux is not the optimal solution. For example, our application is very small, and using Redux at this time may bring additional complexity. Another example is to update the status frequently, which may cause a large number of action to be triggered, which adds additional overhead and complexity. Therefore, for similar scenarios, useReducer might be more appropriate.

so how do we correctly apply useReducer ? This article will give you the answer.

what is useReducer

useReducer is a hook function used to manage the state of components in React. Its function is to decompose the state of the component into multiple values, and to provide a predictable and controllable way to update the state, thus making the code clearer and easier to understand. useReducer is defined as follows:

const [state, dispatch] = useReducer(reducer, initialState);

useReducer accepts two parameters:

  1. reducer : a function that accepts the current state and action (action) , returns the new state . In reducer , you can modify the state according to the type of action .
  2. initialState : the initial value of the state.

useReducer & the return value of nbsp; is an array containing two elements:

  1. state : current status value.
  2. dispatch : a function that triggers status updates. When dispatch is called, the reducer function is triggered, passing the current state and action as arguments.

basic knowledge of useReducer

Let's use a simple counter example to illustrate the basic usage of useReducer :

import React, { useReducer } from 'react';

// define reducer function, which is used to control the change of state.
function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT': // when the type of action is' INCREMENT', add 1 to the status
      return state + 1;
    case 'DECREMENT': // when the type of action is' DECREMENT', the status is minus 1
      return state - 1;
    default: // return to the original state by default
      return state;
  }
}

function Counter() {
  // use the useReducer hook function to manage state
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div>
{/ * render status value in component * /}
<p>Count: {count}</p>
{/ * when the button is clicked, use the dispatch function to trigger the status update * /}
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
}

in the example above, we defined a Counter component to manage the state of a counter. Through the useReducer function, we decompose the state of the component into count values and provide a reducer function to control its changes. When the user clicks the plus or minus button, we trigger the status update through the dispatch function.

when we use useReducer for state management, we must immediately have two of these concepts: state (state) and action (state).

  1. status (state): a state is the data that needs to be managed in a component. The state can be any type of data, such as numbers, strings, objects, and so on.
  2. action (action): an action is an action that triggers a state update. It is a normal JavaScript object with a type attribute and an optional payload attribute. type & the nbsp; attribute is required to specify the type of operation that is triggered. The payload attribute can contain any data that needs to be passed to the reducer function. Typically, the payload attribute is used to specify the data required to update the status.

if you've ever used Redux for state management, it's not hard to find useReducer is similar to Redux in concept and writing. With experience in using Redux, it should not be difficult for you to master useReducer .

comparison with other state management tools

in React, useState , useReducer and Redux are commonly used state management tools. Each of them has its own advantages and disadvantages and is suitable for different scenarios.

  1. useState
    useState is a basic state management tool provided by React. It is very easy to use, you only need to provide the initial value, and you can update the state through the setState function.
    Compared with useReducer , useState has the advantage of being easier to use and suitable for some simple state management scenarios. The downside is that using useState can make the code lengthy and difficult to maintain when the state becomes more complex.
  2. useReducer
    useReducer is another state management tool provided by React. It controls the change of the state through the reducer function, which makes the state update more controllable and predictable.
    Compared with useState , useReducer has the advantage that it can manage more complex states, and state updates are more controllable and predictable. The disadvantage is that compared to useState , using useReducer requires more code, which may have a learning curve for beginners.
  3. Redux
    Redux provides a centralized way of state management. In Redux, all states are stored in a central store , and the state changes are controlled by action and reducer .
    Compared with useState and useReducer , the advantage of Redux is that it can easily manage cross-component states and provides a predictable and controllable way to update states. The disadvantage is that Redux needs to write more code than useState and useReducer , and may add some additional complexity.

understanding the application scenarios in which these tools are applicable is very helpful for us to choose the appropriate state management tools. Using appropriate state management tools in specific scenarios through their respective advantages and disadvantages can greatly improve our development efficiency. Therefore, don't use useReducer blindly.

Summary

through the study of this article, you must have understood the concept and basic usage of useReducer. Before applying it in a real project, it is recommended that you write a few demo yourself to experience useReducer. You can also learn more about the advanced applications of useReducer through official documentation or other articles. After that, we will also write an advanced tutorial on the application of useReducer. You are welcome to follow our official account "Code Flower A" so as not to miss it.

Exit mobile version