Home
React
Advanced Hook: useReducer()
July 29, 2025
1 min

Table Of Contents

01
Idea
02
Where useReducer Really Shines

useReducer it follows the same concept as Redux — but locally, inside a component.

Idea

Instead of directly setting state, you:

  1. Dispatch an action
  2. Let a reducer function decide how state changes

Signature

const [state, dispatch] = useReducer(reducer, initialState)

Where:

  • state → current value
  • dispatch → function to trigger updates
  • reducer → pure function describing how state changes

Example

function counterReducer(state, action) {
switch (action.type) {
case "increment":
return state + 1
case "decrement":
return state - 1
case "reset":
return 0
default:
return state
}
}
function Counter() {
const [count, dispatch] = React.useReducer(counterReducer, 0)
return (
<>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</>
)
}

Where useReducer Really Shines

You’ll benefit most from useReducer when:

const initialState = {
loading: false,
data: null,
error: null
}

Managing this with multiple useState calls becomes messy.

2. State Transitions Are Complex

For example:

  • Loading → Success.
  • Loading → Error.
  • Reset → Idle

Tags

#ReactAdvancedHooks

Share

Related Posts

Advanced Hook
Advanced Hook: flushSync()
July 29, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube