DEV Community

Mohammed Iliass Affani
Mohammed Iliass Affani

Posted on

1

πŸš€ Simplifying State Management in React with useReducer!

When your React components get more complex, managing state with just useState can get messy. This is where useReducer shines! It’s great for handling more complex state logic.
πŸ”Ή Example: Managing a counter with useReducer

import { 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:
      throw new Error();
  }
}

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

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

Enter fullscreen mode Exit fullscreen mode

Why use useReducer?
πŸ”„ Simplifies complex state logic
πŸ”§ Makes state management predictable
πŸš€ Scales better with larger components
πŸ’‘ Have you tried useReducer in your projects? Share your experience or any tips you have! πŸ‘‡

Retry later

Top comments (0)

Retry later
Retry later