What is useReducer?
useReducer is a built-in React Hook used to manage state in a component.
It is an alternative to the useState Hook and is especially useful when the state logic becomes complex or when multiple actions need to update the same state.
Instead of directly updating the state, useReducer uses a reducer function to determine how the state should change based on an action.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
Here:
state – The current state value.
dispatch – A function used to send an action to the reducer.
reducer – A function that determines the next state.
initialState – The initial value of the state.
How Does useReducer Work?
The useReducer Hook follows a simple flow:
- The component starts with an initial state.
- An event occurs, such as clicking a button.
- The dispatch function sends an action.
- The reducer function receives the current state and action.
- The reducer returns the new state.
- React updates the component with the new state.
Example: Counter Using useReducer
import { useReducer } from "react";
const initialState = { count: 0 };
function reducer(state, action)
{
switch (action.type)
{
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset": return initialState;
default: return state;
}
}
function App() {
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 App;
function reducer(state, action) – The reducer function receives the current state and an action to decide how the state should change.
case "increment" – Increases the current count by one and returns the updated state.
case "decrement" – Decreases the current count by one and returns the updated state.
case "reset" – Resets the counter to its initial value, zero.
default: return state; – If the action type doesn't match any case, the current state remains unchanged.
const [state, dispatch] = useReducer(reducer, initialState); – Initializes the reducer and provides the current state (state) and the dispatch function used to send actions.
Top comments (0)