Day 12: Understanding useReducer React Hook
4 mins read

Day 12: Understanding useReducer React Hook

Welcome back to our React Tutorial Series 👋

So far, we’ve explored core React Hooks like useState, useEffect, and useRef. These hooks handle simple state and side effects very well. But as your application grows, you might encounter more complex state logic that involves multiple conditions and actions.

That’s when the useReducer React Hook becomes your best friend.

If you’ve worked with Redux before, useReducer will feel familiar—it’s React’s built-in way to handle state with reducers.


What is the useReducer React Hook?

The useReducer React Hook is an alternative to useState. Instead of updating state directly, you describe how state should change using a function called a reducer.

  • It takes the current state and an action,
  • Processes them in the reducer function,
  • And returns the new state.

Syntax of useReducer

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer: A function (state, action) => newState.
  • initialState: The starting value of your state.
  • state: The current state value.
  • dispatch: A function used to send actions to the reducer.

Example 1: Counter with useReducer React Hook

Let’s build a simple counter with increment, decrement, and reset functionality.

import React, { useReducer } from "react";

// Reducer function
function counterReducer(state, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    case "RESET":
      return { count: 0 };
    default:
      return state;
  }
}

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

  return (
    <div className="p-4">
      <h2 className="text-lg font-bold mb-2">Counter with useReducer React Hook</h2>
      <p className="mb-4">Count: {state.count}</p>
      <button
        onClick={() => dispatch({ type: "INCREMENT" })}
        className="px-3 py-2 bg-green-500 text-white rounded mr-2"
      >
        +
      </button>
      <button
        onClick={() => dispatch({ type: "DECREMENT" })}
        className="px-3 py-2 bg-red-500 text-white rounded mr-2"
      >
        -
      </button>
      <button
        onClick={() => dispatch({ type: "RESET" })}
        className="px-3 py-2 bg-gray-500 text-white rounded"
      >
        Reset
      </button>
    </div>
  );
}

export default Counter;

With useReducer React Hook, all state changes are centralized in the reducer function, making the logic easier to manage.


Example 2: Managing Form State with useReducer React Hook

Handling forms with multiple fields can get messy with useState. Instead, we can use useReducer React Hook for cleaner code.

import React, { useReducer } from "react";

// Reducer for form
function formReducer(state, action) {
  return {
    ...state,
    [action.name]: action.value,
  };
}

function FormExample() {
  const [formState, dispatch] = useReducer(formReducer, {
    name: "",
    email: "",
  });

  const handleChange = (e) => {
    dispatch({ name: e.target.name, value: e.target.value });
  };

  return (
    <div className="p-4">
      <h2 className="text-lg font-bold mb-2">Form with useReducer React Hook</h2>
      <input
        type="text"
        name="name"
        placeholder="Name"
        value={formState.name}
        onChange={handleChange}
        className="border p-2 rounded mb-2 block"
      />
      <input
        type="email"
        name="email"
        placeholder="Email"
        value={formState.email}
        onChange={handleChange}
        className="border p-2 rounded mb-2 block"
      />
      <p className="mt-2">Hello, {formState.name} ({formState.email})</p>
    </div>
  );
}

export default FormExample;

This shows how useReducer React Hook can simplify handling multiple form inputs.


When to Use useReducer React Hook?

Use useReducer when:

  • You have complex state logic (multiple values, conditions).
  • The next state depends on the previous state.
  • You want to keep your state updates predictable and centralized.

Key Differences: useState vs useReducer

FeatureuseStateuseReducer React Hook
ComplexitySimple state logicComplex or structured state logic
State update styleDirect updater functionDispatching actions
Best forBasic counters, togglesForms, authentication, multiple conditions

External Links

🔗 Learn more about useReducer React Hook in the official React docs.


Wrapping Up

Today we explored the useReducer React Hook:

  • It’s an alternative to useState for complex state management.
  • We saw examples with a counter and a form.
  • It keeps state changes predictable and centralized.

👉 Next blog (Day 13) → Custom Hooks in React – we’ll learn how to build reusable logic and make our code cleaner.

Leave a Reply

Your email address will not be published. Required fields are marked *