
What is useReducer ?
useReducer is a React Hook that provides an alternative to useState for managing component state, particularly useful for more complex state logic. It is inspired by the Redux pattern.
useReducer() is a React Hook used to manage complex state logic in function components — especially when:
- State depends on previous state
- You have multiple related state values
- You want a cleaner alternative to useState() for bigger logic
Syntax
const [state, dispatch] = useReducer(reducerFunction, initialState);
- state: current state value
- dispatch: function used to send actions
- reducerFunction: function that updates the state based on the action
Reducer Function
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
Example: Counter with useReducer()
import React, { useReducer } from 'react';
// 1. Reducer function
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
// 2. Component
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: "increment" })}>+1</button>
<button onClick={() => dispatch({ type: "decrement" })}>-1</button>
</>
);
}
When to Use useReducer() vs useState()
Use useState() when... | Use useReducer() when... |
---|---|
You have simple state | You have complex or related state |
You update one value at a time | You need logic based on action types |
One or two useState is enough | State updates depend on previous state |
Summary
Feature | Description |
---|---|
useReducer() | Manages complex state with actions |
dispatch() | Triggers a state update using an action |
reducer() | Pure function to handle state updates |
Alternative to | useState()for complex state logic |
Comments
Add new comment