React.js / React Hooks
Handling Complex State with useReducer
In this tutorial, we will dive into the useReducer React Hook. You will learn how to manage complex state logic in an organized and predictable way with reducers.
Section overview
5 resourcesIntroduces React hooks for functional components to manage state and side effects.
Introduction
In this tutorial, we're going to learn how to manage complex state logic in a React application using the useReducer hook. By the end of this tutorial, you'll be able to:
- Understand what a reducer is and how to use it.
- Understand how to use the
useReducerhook in React. - Apply
useReducerto manage complex state logic in a React application.
Prerequisites:
- Basic knowledge of JavaScript.
- Basic understanding of React.
Step-by-Step Guide
Understanding Reducers
A reducer is a function that takes the current state and an action, and then returns a new state. It’s called a reducer because it’s the type of function you would pass to JavaScript’s Array.prototype.reduce(reducer, ?initialValue) method.
Understanding useReducer
The useReducer is a hook in React that is used for state management. It is an alternative to useState. What useReducer does is it accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.
Example:
import React, { 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};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
export default Counter;
In this example, we're using useReducer to manage the state of a simple counter. When the '+' button is clicked, we dispatch an action of type 'increment', which causes the reducer to increase the count by 1. Similarly, clicking the '-' button dispatches a 'decrement' action, which decreases the count by 1.
Code Examples
Example 1: Managing Multiple State Variables
import React, { useReducer } from 'react';
const initialState = {
firstName: '',
lastName: '',
email: '',
};
function reducer(state, action) {
return {
...state,
[action.name]: action.value,
};
}
function MyForm() {
const [state, dispatch] = useReducer(reducer, initialState);
const handleChange = (event) => {
dispatch(event.target);
};
return (
<form>
<input name="firstName" value={state.firstName} onChange={handleChange} />
<input name="lastName" value={state.lastName} onChange={handleChange} />
<input name="email" value={state.email} onChange={handleChange} />
</form>
);
}
export default MyForm;
In this example, we're using useReducer to manage the state of a form with multiple input fields. Each time the user types into an input field, the handleChange function dispatches an action containing the input's name and current value. The reducer then updates the appropriate field in the state.
Summary
In this tutorial, we learned about reducers and how to use the useReducer hook in React to manage complex state logic. We saw how useReducer can be used to manage multiple state variables and handle complex state transitions.
Practice Exercises
-
Create a to-do list application using
useReducer. The app should allow the user to add new to-dos, mark to-dos as completed, and delete to-dos. -
Create a shopping cart application using
useReducer. The app should allow the user to add items to the cart, increase or decrease the quantity of an item in the cart, and remove items from the cart.
Additional Resources
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article