The power of State Management in React.js
Published: 2023-08-25 21:55:32


![React.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g13sbsvbacvdmjt6of6s.png)

Hello again, and sorry for being late. I had some important tasks in the last few months, but today I am back with an important and exciting topic.
Today we are going to talk about state management in React.js.

---

## Introduction

- One of the most important features of React is state management. It gives React the ability to remember the values even if the component is re-rendered.
- The states are split into local states, global states, server states, and URL states.
Local states are only managed in the current component and cannot be shared across multiple components; they can be managed by 'useReducer' or 'useState'.
- Global states can be shared across multiple components. For that, we can use the React Context API (which will be discussed in another article) or Third-party libraries.
- There are many ways to handle state in React, and we will discuss most of them today.

## 1. UseState hook
- 'useState' is a built-in hook in React. Its main purpose is to store the state, and it has the ability to remember or change it in every render.

> Note: state is a normal value but controlled by React

- 'useState' accepts one argument: the state, and returns two values in an array: the variable that will store the value and the method that can be used to change or set the value (that's why we call it the setter method).
- The convention for naming the setter method is to use 'set' at the beginning, followed by the variable name.

```
import {useState} from 'react';

function stateManagement() {
  const [variable, setVariable] = useState('any value');
  .
  .
  .
}
```

## 2. useReducer hook
- Another valuable hook in React is 'useReducer'. It is similar to useState', but with more features.
- If you want to manage the state based on conditions or complex logic, then 'useReducer' is the appropriate way.
- It accepts two arguments: the reducer function and the initial state, and returns the variable that holds the state and the dispatch method.
- The reducer function contains the logic that changes the state, and it has two parameters: the state and the action (the action is passed to the dispatch method in order to connect the reducer and dispatch methods, which gives us the ability to change the state based on the particular logic).
- The dispatch method is used to change the state based on its argument, which is the action (the action is usually an object that has some helpful properties in the logic)

> Note: developers usually use 'type' property in the action to describe the type of changing in the state

- An example from w3schools:

```
import { useReducer } from "react";

the initial state
const initialTodos = [
  {
    id: 1,
    title: "Todo 1",
    complete: false,
  },
  {
    id: 2,
    title: "Todo 2",
    complete: false,
  },
];

// the reducer method
const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};

function Todos() {
  // calling useReducer
  const [todos, dispatch] = useReducer(reducer, initialTodos);

  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };

  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}
```

## 3. Libraries
- There are third-party libraries used to manage global states.
- For example, we have libraries like Redux, Recoil, and Zustand.
- I recommend the Redux library. You should learn the Redux toolkit first, then move on to using Redux in React using 'React-Redux'.

---

## Summary
- We have many ways to manage states, and each has its own uses. So, make sure to know what type of state you need to manage and how to manage it, then choose the appropriate way to do that.
- There are server states (which manage the data coming from the server) and URL states (which are the data in URLs that existed in the pathname and query parameters), we can discuss them in another topic.

Thanks for Reading and I hope you enjoyed today's topic and learned something, Goodbye ❤️.