React JS Reducer
- coding z2m
- Dec 24, 2024
- 2 min read
Updated: Jan 24

React JS Reducer
React JS Reducer: The useReducer hook in React is a powerful tool for managing complex state logic in functional components. It is an alternative to the useState hook, particularly useful when the state depends on multiple actions or has intricate transitions.
Key Concepts
Reducer Function: A pure function that takes the current state and an action as arguments and returns a new state based on the action type.
Action: An object that describes the type of state change and may include additional data (payload).
State Management: useReducer centralizes state logic, making it easier to manage complex state transitions.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
reducer: The reducer function.
initialState: The initial value of the state.
state: The current state value.
dispatch: A function used to dispatch actions.
Code Example
Let’s create a simple counter with increment, decrement, and reset actions:
/* Define the Initial State
The initialState is an object. This structure defines the shape of the state object. Here, count is a property of the state object, initially set to 0. */
const initialState = { count: 0 };
/* Reducer Function Logic: When the INCREMENT action is dispatched, the reducer receives the current state object (e.g., { count: 0 }) and creates a new state object by modifying the count property: */
function counterReducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
}
/* State in useReducer: The state variable, returned by the useReducer hook, starts with the value of initialState. It is updated by the reducer function based on the actions dispatched.
*/
function Counter() {
const [state, dispatch] = useReducer(counterReducer, initialState);
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
</div>
);
}
Breaking Down the Example
Initial State: initialState is { count: 0 }.
Reducer Logic:
INCREMENT: Adds 1 to the count.
DECREMENT: Subtracts 1 from the count.
RESET: Resets the count to 0.
Dispatch Actions: The dispatch function triggers state changes by passing an action object (e.g., { type: "INCREMENT" }).
Comments