Raja Muhammad Asher
Raja Muhammad Asher


Raja Muhammad Asher

React useReducer Hook

Photo by Lautaro Andreani on Unsplash

React useReducer Hook

Raja Muhammad Asher's photo
Raja Muhammad Asher
·Feb 2, 2023·

2 min read

The useReducer hook is a built-in hook in React that allows you to manage complex state logic in your application. It's an alternative to the useState hook that provides more flexibility and control over state management.

The useReducer hook takes two arguments: a reducer function and an initial state. The reducer function is responsible for updating the state based on actions that are dispatched to it. The initial state argument is the starting value for the state.

Here's an example of how to use the useReducer hook:

import React, { useReducer } from 'react';

const initialState = { count: 0 };

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, initialState);

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

In this example, we define an initial state object with a count property set to 0. We also define a reducer function that takes a state and an action as arguments and returns a new state based on the action type.

In the Counter component, we call the useReducer hook with the reducer function and initialState as arguments. This returns an array with two values: the current state and a dispatch function. The dispatch function is used to send actions to the reducer, which updates the state accordingly.

Finally, we render the current count value and two buttons that dispatch increment and decrement actions when clicked, respectively.

That's a simple example of how to use the useReducer hook in React. With this hook, you can handle more complex state updates in your application with ease.

Share this