useReducer

Subject: React

πŸ” What is useReducer?

useReducer is a React Hook used to manage complex or structured state logic. It’s inspired by Redux but built into React β€” no external library required.

Think of it as a more organized, scalable version of useState when you're dealing with multiple related state values or action types.


🧠 When to Use useReducer

SituationUse useReducer?
State has multiple sub-valuesβœ… Yes
Many types of updates neededβœ… Yes
Complex state update logicβœ… Yes
Simple field or counter❌ Use useState instead

πŸ“¦ Syntax

  • state: Current value
  • dispatch(action): Function to send an action
  • reducerFunction: Logic that handles actions
  • initialState: Default state value

βœ… Example: Counter Using useReducer


🧠 Logic Breakdown

  • Initial state: { count: 0 }
  • Clicking a button dispatches an action (e.g. { type: "INCREMENT" })
  • Reducer returns new state
  • React re-renders the UI

βœ… Example: Form with Multiple Fields


⚠️ Best Practices

βœ… Do❌ Don’t
Keep reducer pure (no side effects)Don't call APIs or fetch inside reducer
Use action.type + optional payloadAvoid deeply nested reducer logic
Group related state togetherDon't use for overly simple states
Combine with useContext for global useDon’t repeat reducers in every component

🧩 Real-Life Use Cases

Use CaseWhy useReducer Works Well
Forms with many fieldsOne centralized logic for updates
Complex togglesCombine into one reducer
Game stateManage scores, levels, status
App-wide global statePair with useContext for sharing

πŸ§ͺ Bonus: Action Shape

  • type: describes the action
  • payload: data needed to update the state

πŸ“Œ Summary Table

FeatureDescription
useReducer()Hook to manage complex or structured state
reducer()Pure function to update state based on action type
dispatch()Function to send action and update state
initialStateThe default state object or value
BenefitClean, scalable, and testable logic

πŸ‘‰ Great next step: Learn how to combine useReducer with useContext for a full app-level state manager.