| Diagnose Blank Screen in React :👈 | 👉:useEffect vs useLayoutEffect |
useState vs useReducer: Which Should You Use? |
useState vs useReducer: Which Should You Use in React?
1. Quick Answer
Both useState and useReducer are React Hooks used to manage component state. The main difference is how they organize state updates.
- useState: Best for simple, independent state values such as input fields, toggles, counters, and loading indicators.
- useReducer: Best for complex state logic involving multiple related values, several update actions, or transitions that depend on the current state.
Rule of thumb: Start with useState. Use useReducer when state transitions become complicated or when you want to centralize state-update logic.
2. Table of Contents
- Understanding State Management
- What Is useState?
- What Is useReducer?
- useState vs useReducer Comparison
- Example 1: Counter Using Both Hooks
- Example 2: Managing a Form
- Example 3: Managing Complex State
- How to Choose the Right Hook
- Common Mistakes
- Performance Considerations
- Best Practices
- Interview Questions
- Summary
3. Understanding State Management
In React, state is data that a component remembers between renders. When state changes, React can render the component again to display the updated data.
For example, a component might maintain:
- A counter value.
- Whether a dialog is open.
- A user's name and email.
- Whether data is loading.
- A shopping cart containing multiple products.
React provides different ways to manage this state. Two commonly used options are useState and useReducer.
Conceptual Flow
4. What Is useState?
useState is a React Hook that allows a functional component to store and update a state value.
Syntax
const [state, setState] = useState(initialState);
state: The current state value.setState: The function used to request a state update.initialState: The initial value used when the component initializes.
Example: Counter Using useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
Decrement
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}
export default Counter;
How It Works
- The initial value of
countis0. - Clicking Increment requests an update to
count + 1. - Clicking Decrement requests an update to
count - 1. - Clicking Reset requests an update to
0. - React renders the component with the updated state.
When Is useState Suitable?
- Managing a counter.
- Opening and closing a modal.
- Showing or hiding a password.
- Managing an input field.
- Tracking a loading indicator.
- Managing a small number of independent state values.
5. What Is useReducer?
useReducer is a React Hook that manages state using a reducer function. Instead of updating the state directly through a setter, a component dispatches an action describing what happened. The reducer calculates the next state.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
state: The current state.dispatch: The function used to dispatch an action.reducer: A function that calculates the next state from the current state and an action.initialState: The initial state value.
Reducer Function Syntax
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
case "RESET":
return { ...state, count: 0 };
default:
return state;
}
}
A reducer receives the current state and an action, then returns the next state. It should be a pure function: it must not mutate the existing state or perform side effects such as API calls.
Example: Counter Using useReducer
import { useReducer } from "react";
const initialState = {
count: 0
};
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return {
...state,
count: state.count + 1
};
case "DECREMENT":
return {
...state,
count: state.count - 1
};
case "RESET":
return {
...state,
count: 0
};
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(
reducer,
initialState
);
return (
<div>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: "INCREMENT" })}>
Increment
</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>
Decrement
</button>
<button onClick={() => dispatch({ type: "RESET" })}>
Reset
</button>
</div>
);
}
export default Counter;
How It Works
- The component initializes the state with
{ count: 0 }. - When the user clicks Increment, the component dispatches an
INCREMENTaction. - React calls the reducer with the current state and the action.
- The reducer calculates and returns the next state.
- React renders the component with the updated state.
For this simple counter, both hooks work well. The reducer version becomes more useful when the number of actions and the complexity of the state transitions increase.
6. useState vs useReducer Comparison
| Feature | useState | useReducer |
|---|---|---|
| Basic purpose | Manages a state value. | Manages state through a reducer function. |
| Update mechanism | Uses a setter function. | Dispatches actions processed by a reducer. |
| Best suited for | Simple or independent state updates. | Complex or related state transitions. |
| Learning curve | Generally easier to understand. | Requires understanding actions and reducers. |
| Code organization | Update logic is often near the component. | Update logic can be centralized in the reducer. |
| Multiple related values | Can manage them using objects or multiple state variables. | Can coordinate changes to multiple values in one transition. |
| Testing update logic | Often requires testing the component or extracted logic. | The reducer can be tested as a standalone pure function. |
| Performance | Usually sufficient for simple state. | Not automatically faster; performance depends on the component and update patterns. |
| Boilerplate | Usually less code for simple updates. | Usually more structure because of actions and reducer logic. |
| Typical examples | Input value, toggle, selected tab, counter. | Multi-step forms, complex filters, shopping cart state. |
7. Example 1: Counter Using Both Hooks
Consider a counter that supports increment, decrement, and reset.
Using useState
const [count, setCount] = useState(0);
function increment() {
setCount(currentCount => currentCount + 1);
}
function decrement() {
setCount(currentCount => currentCount - 1);
}
function reset() {
setCount(0);
}
Using useReducer
const [count, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
case "RESET":
return 0;
default:
return state;
}
},
0
);
function increment() {
dispatch({ type: "INCREMENT" });
}
function decrement() {
dispatch({ type: "DECREMENT" });
}
function reset() {
dispatch({ type: "RESET" });
}
Which is better here? Both are valid. For a simple counter, useState is usually more straightforward. A reducer may be appropriate if the counter later gains many actions, rules, or related state values.
8. Example 2: Managing a Form
Suppose a form contains a name, email address, and submission status.
Using useState
import { useState } from "react";
function UserForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [status, setStatus] = useState("idle");
function handleSubmit(event) {
event.preventDefault();
setStatus("submitting");
// Perform form submission here.
}
return (
<form onSubmit={handleSubmit}>
<input
value={name}
onChange={event => setName(event.target.value)}
placeholder="Name"
/>
<input
value={email}
onChange={event => setEmail(event.target.value)}
placeholder="Email"
/>
<button type="submit" disabled={status === "submitting"}>
Submit
</button>
<p>Status: {status}</p>
</form>
);
}
export default UserForm;
This approach is easy to read because the state values are relatively independent. As validation, error handling, submission, and reset rules become more interconnected, a reducer may provide a clearer structure.
Using useReducer
import { useReducer } from "react";
const initialState = {
name: "",
email: "",
status: "idle",
error: ""
};
function formReducer(state, action) {
switch (action.type) {
case "FIELD_CHANGED":
return {
...state,
[action.field]: action.value,
error: ""
};
case "SUBMIT_STARTED":
return {
...state,
status: "submitting",
error: ""
};
case "SUBMIT_SUCCEEDED":
return {
...state,
status: "success"
};
case "SUBMIT_FAILED":
return {
...state,
status: "error",
error: action.message
};
case "RESET":
return initialState;
default:
return state;
}
}
function UserForm() {
const [state, dispatch] = useReducer(
formReducer,
initialState
);
function handleSubmit(event) {
event.preventDefault();
dispatch({ type: "SUBMIT_STARTED" });
// An actual API request and its success/error handling
// would dispatch SUBMIT_SUCCEEDED or SUBMIT_FAILED.
}
return (
<form onSubmit={handleSubmit}>
<input
value={state.name}
onChange={event =>
dispatch({
type: "FIELD_CHANGED",
field: "name",
value: event.target.value
})
}
placeholder="Name"
/>
<input
value={state.email}
onChange={event =>
dispatch({
type: "FIELD_CHANGED",
field: "email",
value: event.target.value
})
}
placeholder="Email"
/>
<button
type="submit"
disabled={state.status === "submitting"}
>
Submit
</button>
<p>Status: {state.status}</p>
<p>{state.error}</p>
</form>
);
}
export default UserForm;
This example demonstrates how a reducer centralizes state transitions. It is illustrative rather than a complete form submission implementation: an API request, validation, and success/error dispatches still need to be added.
9. Example 3: Managing Complex State
Consider a shopping cart. Each cart item has a product ID, name, quantity, and price. The cart supports adding products, changing quantities, removing products, and clearing the cart.
These actions affect related state and may require consistent rules. A reducer is a good fit for this type of logic.
Shopping Cart Reducer
import { useReducer } from "react";
const initialState = {
items: []
};
function cartReducer(state, action) {
switch (action.type) {
case "ADD_ITEM": {
const existingItem = state.items.find(
item => item.id === action.item.id
);
if (existingItem) {
return {
...state,
items: state.items.map(item =>
item.id === action.item.id
? { ...item, quantity: item.quantity + 1 }
: item
)
};
}
return {
...state,
items: [
...state.items,
{ ...action.item, quantity: 1 }
]
};
}
case "REMOVE_ITEM":
return {
...state,
items: state.items.filter(
item => item.id !== action.id
)
};
case "CHANGE_QUANTITY":
return {
...state,
items: state.items.map(item =>
item.id === action.id
? {
...item,
quantity: Math.max(1, action.quantity)
}
: item
)
};
case "CLEAR_CART":
return {
...state,
items: []
};
default:
return state;
}
}
function ShoppingCart() {
const [state, dispatch] = useReducer(
cartReducer,
initialState
);
const product = {
id: 1,
name: "Keyboard",
price: 1500
};
const total = state.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
return (
<div>
<button
onClick={() =>
dispatch({
type: "ADD_ITEM",
item: product
})
}
>
Add Keyboard
</button>
<ul>
{state.items.map(item => (
<li key={item.id}>
{item.name} - Quantity: {item.quantity}
<button
onClick={() =>
dispatch({
type: "CHANGE_QUANTITY",
id: item.id,
quantity: item.quantity + 1
})
}
>
+
</button>
<button
onClick={() =>
dispatch({
type: "REMOVE_ITEM",
id: item.id
})
}
>
Remove
</button>
</li>
))}
</ul>
<p>Total: ₹{total}</p>
<button
onClick={() => dispatch({ type: "CLEAR_CART" })}
>
Clear Cart
</button>
</div>
);
}
export default ShoppingCart;
Why Is useReducer Useful Here?
- All cart update rules are in one reducer.
- Each action clearly describes the operation being performed.
- Related changes are calculated from the same current state.
- The reducer can be tested independently from the UI.
- New operations, such as applying a discount, can be added as separate actions.
Important: The reducer should manage the cart's state transitions, not perform side effects such as API calls or payment processing. Those operations belong in appropriate event handlers, effects, or other application logic.
10. How to Choose the Right Hook
Decision Guide
Choose useState When
- You have a single value or a few independent values.
- The update logic is simple and easy to understand.
- You want the smallest amount of code.
- You are managing input fields, toggles, counters, or visibility.
Choose useReducer When
- Many actions update the same state object.
- Several state values must change together.
- State transitions have business rules or conditions.
- You want to separate state-transition logic from UI event handlers.
- You need to test state transitions independently.
Can You Use Both?
Yes. A component can use both hooks. For example, a shopping cart component might use useReducer for cart items and useState for whether a confirmation dialog is open.
const [cart, dispatch] = useReducer(cartReducer, initialCart);
const [isDialogOpen, setIsDialogOpen] = useState(false);
Choose each hook based on the state it manages rather than forcing the entire component to use only one approach.
11. Common Mistakes
Mistake 1: Mutating State in a Reducer
Incorrect:
function reducer(state, action) {
state.count++;
return state;
}
This mutates the existing state object and returns the same reference. React state should be treated as immutable.
Correct:
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return {
...state,
count: state.count + 1
};
default:
return state;
}
}
Mistake 2: Forgetting to Return the New State
A reducer must return the next state for each handled action. If a branch returns undefined, the component may break when it tries to read properties from the state.
Always handle expected actions and include a sensible default branch.
Mistake 3: Using useReducer for Every State Value
Not every state update needs an action and reducer. Using useReducer for a simple toggle can introduce unnecessary code.
Simple toggle with useState:
const [isOpen, setIsOpen] = useState(false);
function toggle() {
setIsOpen(current => !current);
}
Mistake 4: Treating dispatch as an Immediate State Update
Dispatching an action requests a state update. It does not immediately change the state variable captured by the current render.
dispatch({ type: "INCREMENT" });
// This still refers to the state value from the current render.
console.log(state.count);
Use the updated state during a subsequent render. If you need to calculate a value for the next state, put that calculation in the reducer rather than expecting dispatch to return the new state.
Mistake 5: Performing Side Effects Inside a Reducer
A reducer should be a pure function. Avoid API calls, timers, logging that must happen exactly once, and other side effects inside the reducer.
Incorrect approach: Dispatch an action and make an API request from inside the reducer.
Better approach: Perform the request in an event handler or an appropriate effect, then dispatch an action with the result.
Mistake 6: Forgetting Immutable Updates for Nested Objects
Copying only the top-level object is not enough if you mutate a nested object that is shared with the previous state.
Incorrect:
return {
...state,
user: {
...state.user,
address: {
...state.user.address,
city: "Hyderabad"
}
}
};
The code above is actually the correct immutable update pattern. The mistake would be modifying state.user.address.city directly. For nested state, copy each object along the path to the changed value.
12. Performance Considerations
Neither hook is automatically faster in every situation. Choose based primarily on clarity and the complexity of the state logic.
- useState: Often simpler and sufficient for small state values.
- useReducer: Can make complex update logic easier to maintain, but introduces action dispatching and reducer execution.
- Rendering: Both hooks can trigger a component render when state changes. A reducer does not automatically prevent unnecessary renders.
- State structure: Avoid putting unrelated state values into one large state object without a good reason.
- Memoization: Use tools such as
memo,useMemo, oruseCallbackonly when there is a measured or understood need.
React can skip an update when the next state is identical to the current state according to Object.is, although React may still call a component before skipping further work in some circumstances. Do not rely on mutating existing state to trigger an update.
What About Context?
useReducer is sometimes combined with React Context to share state and dispatch across a component tree. This can help organize application state without passing props through many intermediate components.
However, Context is not a replacement for every state-management solution. When context values change, consumers of those values may re-render. For large or performance-sensitive applications, consider state ownership, context splitting, and whether a dedicated state-management library is justified.
13. Best Practices
- Start with
useStatewhen the state logic is straightforward. - Move to
useReducerwhen related transitions become difficult to follow. - Give actions meaningful names such as
ADD_ITEM,SUBMIT_STARTED, andRESET. - Keep reducers pure and return immutable state updates.
- Use action payloads to provide the data needed for a transition.
- Keep API requests and other side effects outside reducers.
- Avoid duplicating values in state when they can be calculated from existing state.
- Test reducers with representative states and actions.
- Use TypeScript discriminated unions for actions in larger applications to improve type safety.
- Do not adopt a more complicated state-management pattern merely because an application is growing; introduce complexity when it solves a real problem.
14. Interview Questions
Q1. What is the main difference between useState and useReducer?
Answer: useState updates state using a setter function, while useReducer dispatches actions that a reducer processes to calculate the next state.
Q2. When should you use useReducer instead of useState?
Answer: Use useReducer when state transitions are complex, multiple related values change together, or centralizing update logic improves maintainability and testability.
Q3. Is useReducer faster than useState?
Answer: Not inherently. Both can trigger component renders when state changes. Performance depends on the state structure, component tree, and rendering behavior.
Q4. Can useReducer manage multiple state values?
Answer: Yes. The reducer can manage an object or another data structure containing multiple related values and update them together.
Q5. Can a reducer perform an API call?
Answer: A reducer should be a pure function and should not perform API calls. Perform side effects outside the reducer and dispatch an action with the result.
Q6. Can a component use both useState and useReducer?
Answer: Yes. For example, useReducer can manage complex cart state while useState controls whether a confirmation dialog is open.
Q7. What does dispatch do?
Answer: dispatch sends an action to the reducer so React can calculate the next state. It does not synchronously return the updated state value.
Q8. Why should reducers be pure functions?
Answer: Pure reducers produce predictable state transitions for the same inputs, are easier to test, and avoid problems caused by mutations or side effects. React may call reducers more than once in development Strict Mode to help detect accidental impurities.
15. Summary
| Situation | Recommended Hook | Reason |
|---|---|---|
| Counter | useState | Simple state and updates. |
| Show or hide a dialog | useState | One independent boolean value. |
| Input field | useState | Simple, direct updates. |
| Complex form workflow | useReducer | Related fields, validation, and submission transitions can be centralized. |
| Shopping cart | useReducer | Multiple actions affect related state. |
| Complex state shared through Context | useReducer + Context | Can centralize transitions and share state across components. |
Final recommendation: Use useState for simple state and useReducer for complex state transitions. Both are valid tools; the best choice is the one that keeps your component logic clear, predictable, and maintainable.
| Diagnose Blank Screen in React :👈 | 👉:useEffect vs useLayoutEffect |
Comments and Discussion