React useReducer Hook

  • Share this:

The `useReducer` hook is a way to manage the state in a React functional component. It is similar to the `useState` hook, but it allows you to manage complex state objects and perform actions that update the state. It is often used as an alternative to the `useState` hook when the state object is large or the state update logic is complex.

The `useReducer` hook takes two arguments: a reducer function and an initial state. The reducer function is a pure function that takes the current state and an action and returns the new state. The initial state is the state of the component when it is first rendered.

Here is an example of how you might use the `useReducer` hook to manage a counter in a React component:

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
      throw new Error();

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>

In this example, the `useReducer` hook returns an array containing the current state and a dispatch function. The dispatch function is used to update the state by calling the reducer function with an action. The reducer function uses a switch statement to determine how to update the state based on the action type.

The `useReducer` hook can be a powerful tool for managing the state in a functional component, especially when the state is complex or the update logic is complex. It can make it easier to understand the flow of data in a component and can make the code more scalable as the component grows in complexity.



About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.