How To Use useReducer Hook In React? See Example

What Is useReducer?

The useReducer hook is an alternative to useState for managing complex state logic.
It uses a reducer function to update state based on actions.


Basic Syntax

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer(state, action) → returns new state
  • dispatch(action) → triggers state update

Example: Counter Using useReducer

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 };
    default:
      return state;
  }
}

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

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

export default App;

✅ State updates are handled via dispatch with action objects.


Key Points

  • Ideal for complex or nested state
  • State updates are predictable using reducer logic
  • Works well with multiple related actions
  • Similar to Redux reducer concept

Conclusion

useReducer helps manage complex state efficiently in functional components and keeps state logic centralized.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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