useReducer in react

useReducer hook is an alternative way to manage state in React application. useState hook is suitable for managing simple states. here is why you should consider using useReducer hook over useState.
  • When state is a complex object, it is easier to manage state
  • When new state depends on previous state, it is easy to update state
  • Single reducer functions can handle multiple action types
Here is a sample example using useReducer hook in react.

import { useReducer } from "react";
const counterReducer = (state, action) => {
  console.log(state, action);
  switch (action.type) {
    case "INCREMENT":
      return { ...state, count: state.count + 1 };
    case "DECREMENT":
      return { ...state, count: state.count - 1 };
      return state;

export default function App() {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });
  return (
      <h1>Counter example using useReducer hook</h1>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>

Complex problems, Simple Solutions