The useReducer Hook is used to manage state in React applications. It is especially useful when a component has complex state logic or multiple state updates.
useReducer helps us manage state by keeping all the state updating logic in one place.
Instead of directly updating the state, we dispatch an action. The reducer function checks that action and returns the new state.
For example, imagine a counter application.
We need three operations:
Increment the count.
Decrement the count.
Reset the count.
We can implement these operations using useState. But when the application has many state updates, managing all the logic inside event handlers can become difficult.
Syntax of useReducer
import { useReducer } from "react";
const [state, dispatch] = useReducer(reducer, initialState);
state: Stores the current state value.
dispatch: Function used to send an action to the reducer.
reducer: Function that decides how the state should change.
initialState: The starting value of the state.
How does useReducer work?
First, we create an initial state.
We create a reducer function.
The user performs an action, such as clicking a button.
We call dispatch() with the required action.
The reducer receives the current state and action.
The reducer returns the updated state.
React renders the component with the new state.
Top comments (0)