🪝useReducer Hook🪝

🪝useReducer Hook🪝

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

useReducer is a built-in React hook.

In this article, you will learn what the useReducer hook is, what it is used for, when to choose the useReducer hook, and when to choose the useState hook😄.

Introduction

The useReducer hook allows you to manage the state in a functional component and provides a function that updates the state and re-renders the component.

Oh! but don't we already have a useState hook to handle state management in React?🤔

Well, yes!😉

useState does the job pretty well. However, the useState hook is limited in cases where a component needs a complex state structure and proper sync with the tree😯.

useReducer when combined with the useContext hook could behave very similarly to Redux pattern and sometimes might be a better approach for global state management instead of other unofficial libraries such as Redux🤫. As a matter of fact, the useReducer's API itself was used to create a simpler useState hook for state management.

According to React's official docs :

"An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method."

What is useReduser🤔

useReducer()🚀 is a React.js Hook that manages a complex state in your application and updates it based on the 'action' you send.

It does very similar to setState, It's a different way to manage the state using Redux Pattern.It very similar to Redux if you want to not use a 3rd-party library.

Instead of updating the state directly, we dispatch actions, that go to a reducer function, and this function figures out, how to compute the next state.

ACTION.png

Choosing between useReducer and useState🔎

In simple words:😊

  • useReducer is better when you have kind of connected and complex states. You can write some logic that basically runs whenever you want to change the state to do more complex updates than just setting a new value👍.

  • useState is better when your states are NOT complex and interdependent. In these cases, using useState makes your code much shorter and easier🚀 to understand than using useReducer.

Steps for useReduser

You should import useReducer from react js

import React, { useReducer } from 'react';

useReducer Hook accepts a reducer function and an initial state.

It returns an array with 2 values:

The first one is the state value, and the second value is the dispatch function which is used to trigger an action with the help of ES6 destructuring.

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

Where:

  • state: the state returned by useReducer.

  • dispatch: a function used to update the state.

  • reducer:

  • A function that takes 2 arguments: the first one is the previous state and the second one is an action which is an object containing information used for updating the state (This explanation can be a little confusing. Don’t worry, the examples given in this article will show it’s not that complicated).

  • initialState: The initial state that we want to start working on it

Let's see a simple Counter example using useReduser

import React, { useReducer } from "react";

const initialState = 0;

const reducer = (state, action) => {
  switch (action) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return initialState;
    default:
      return state;
  }
}

function App() {
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <div className="App">
      <h3>useReducer in React Hook</h3>
      <span>Counter: {count}</span><br />
      <button onClick={() => dispatch('increment')}>Increment</button>
      <button onClick={() => dispatch('decrement')}>Decrement</button>
      <button onClick={() => dispatch('reset')}>Reset</button>
    </div>
  );
}

export default App;

That’s it for today.

Thank you for reading. Happy Coding..!! 🙂

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!