0% completed
We've seen how states work and its importance in building React applications that are dynamic and maintainable. While the useState
hook is often sufficient for simple state management, complex state logic calls for a more structured approach. This is where the useReducer
hook comes in. It is a powerful alternative that simplifies complex state transitions in functional components.
What is the useReducer hook
The useReducer
hook is a state management tool in React that allows you manage state logic by using a reducer function. The useReducer helps you transition state from one form to another in response to dispatched actions.
Syntax
The useReducer
is written in this pattern:
const [state, dispatch] = useReducer(reducer, initialState);
Here we have:
Let's look at a simple counter example to understand how the useReducer
works. The entire process would be broken down into steps for you to grasp it better.
Step One: Define the Reducer Function
A reducer function takes two parameters: the current state and the action. Based on the action type, it returns the updated state.
const counterReducer = (state, action) => { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; case "reset": return { count: 0 }; default: throw new Error(`Unknown action: ${action.type}`); } };
In this reducer function:
Two parameters are taken, which are:
A switch statement is used to determine which action to process based on the action.type
In the switch statement, we have the following cases:
{ count: state.count + 1 }
.{ count: state.count - 1 }
.{ count: 0 }
.Unknown action: ${action.type}
.The main purpose of this reducer function is to update the count value in the state based on specific actions like increment, decrement, and reset.
Step Two: Initialize State with useReducer
After creating our reducer function, we now initialize the state using the useReducer
hook.
import React, { useReducer } from "react"; export default function Counter(){ const initialState = { count: 0 }; 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> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> ); };
In this code example:
useReducer
hook from React.<h1>
element displaying the current count value (state.count) and three <button>
elements, each with an onClick
event handler that dispatches different actionsThese buttons are:
Output
Having successfully created our Counter component with its reducer function using the useReducer
hook, here is how it displays on the browser:
How does the useReducer compare to useState
The hooks share common similarities such as:
Why use useReducer Over useState?
While useState is excellent for simple state management, useReducer is best suited in scenarios like:
.....
.....
.....