Difference between useState and useReducer hooks
Both useState
and useReducer
are Hooks for managing state, but they are suited for different situations:
Aspect | useState | useReducer |
---|---|---|
Usage | Simple state (strings, numbers, booleans, objects) | Complex state logic involving multiple sub-values or transitions |
Parameters | Initial state value | Reducer function + initial state |
Updates | Directly using the state setter | Dispatching actions to modify state |
Best for | Small, straightforward updates | Complex updates, dependent states, or when the next state depends heavily on the previous one |
Example use case:
useState
→ toggling a modal.useReducer
→ managing a shopping cart.
Example for useState
Suppose you want to manage a simple counter:
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }
✅ Here:
useState(0)
initializescount
to0
.setCount
updates thecount
.- Every time
setCount
is called, the component re-renders.
Example for useReducer
Suppose the counter has more complex logic (increment, decrement, and reset):
import { useReducer } from 'react'; // Reducer function function counterReducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; case 'reset': return { count: 0 }; default: throw new Error(); } } function CounterWithReducer() { const [state, dispatch] = useReducer(counterReducer, { count: 0 }); return ( <> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> <button onClick={() => dispatch({ type: 'reset' })}>Reset</button> </> ); }
✅ Here:
useReducer(counterReducer, { count: 0 })
initializes state.dispatch
is used to send actions to the reducer.- The reducer updates the state based on action type.
Quick visual:
When to prefer | Example |
---|---|
useState | Simple toggles, input field values |
useReducer | Forms with multiple fields, complex state transitions, multiple related values |