Day 29 of My React Learning Journey - Understanding useReducer and why we use it instead of useState
1. What is useReducer in React? useReducer is a ReactHook used to manage state in a component.It is useful when state management invloves multiple actions or more complex logic. _ Syntax:_ const[state,dispatch] = useRe
1. What is useReducer in React?
useReducer is a ReactHook used to manage state in a component.It is useful when state management invloves multiple actions or more complex logic.
_
Syntax:_
const[state,dispatch] = useReducer(reducer,intialState);
state: stores the current value.
dispatch: Sends an action to the reducer function.
reducer: A function that decides how the state should change.
**initialState: **The starting value of the state.
2.useReducer Example:
import { useReducer } from "react";
const initialState = 0;
function reducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
case "reset":
return initialState;
default:
return state;
}
}
function App() {
const [count, dispatch] = useReducer(
reducer,
initialState
);
return (
<div>
<h2>Count: {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 App;
working process:
1.initial state sets the starting counter value to zero.
2.reducer receives the current state and action.
3.switch checks the action type.
4.dispatch sends an action to the reducer.
5.The reducer return the new state.
6.React updates the component with the new count.
**
3.Why use UseReducer Instead of useState?
useState:
- Good for simple state.
- Updates state using a setter function.
- State logic is often written in the component.
- Simple to understand. Ex:Toggle buttons,Input fields,Simple counters.
_useReducer:
- Useful for complex state logic.
- Updates state using dispatch and a reducer
- State logic is organized inside a reducer function.
- Useful when there are multiple actions. Ex:Shopping cart operations,Multiple counter actions,Forms with multiple related state updates.
4.What i Learned Today
- Today i understood that what useReducer is,how its reducer function works,how dispatch sends action to update state.
- useReducer an be useful when state logic becomes more complex than a simple useState update.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.