The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
- reducer: A function that defines how the state should be updated based on the action. It takes two parameters: the current state and the action.
- initialState: The initial value of the state.
- State The current state returned from the useReducer hook.
- dispatch: A function used to send an action to the reducer to update the state.
Implementing the useReducer hook
1. Basic Counter using useReducer
A common example of using useReducer is managing the state of a counter with actions to increment and decrement the value.
JavaScript
import React, { useReducer } from 'react';
const counterReducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}
export default Counter;
Output
Counter appIn this example
- counterReducer: A reducer function that handles two actions, INCREMENT and DECREMENT, updating the count value accordingly.
- dispatch: This function triggers the reducer with the action type (INCREMENT or DECREMENT), which updates the state.
2. Managing Complex State with Multiple Actions
For more complex state management, you can use useReducer to handle actions that affect different parts of the state, such as managing a form or multiple values at once.
JavaScript
import React, { useReducer } from 'react';
const initialState = { name: '', age: 0, submitted: false };
const formReducer = (state, action) => {
switch (action.type) {
case 'SET_NAME':
return { ...state, name: action.payload };
case 'SET_AGE':
return { ...state, age: action.payload };
case 'SUBMIT':
return { ...state, submitted: true };
default:
return state;
}
};
function Form() {
const [state, dispatch] = useReducer(formReducer, initialState);
const handleSubmit = () => {
dispatch({ type: 'SUBMIT' });
};
return (
<div>
<input
type="text"
value={state.name}
onChange={(e) => dispatch({ type: 'SET_NAME', payload: e.target.value })}
placeholder="Enter your name"
/>
<input
type="number"
value={state.age}
onChange={(e) => dispatch({ type: 'SET_AGE', payload: e.target.value })}
placeholder="Enter your age"
/>
<button onClick={handleSubmit}>Submit</button>
{state.submitted && <p>Form Submitted!</p>}
</div>
);
}
export default Form;
Output
In this example
- formReducer: The reducer function handles three actions: SET_NAME, SET_AGE, and SUBMIT. Each action updates the corresponding part of the state.
- dispatch: Dispatches actions to modify the state (e.g., setting the name or age, or marking the form as submitted).
Interesting Things About the useReducer Hook
- Manages Complex State Logic: Unlike useState, which is ideal for simple state updates, useReducer is more suited for handling complex state logic that involves multiple sub-values or intricate state transitions.
- Improves Performance in Large Applications: Since useReducer allows state updates based on dispatch actions, it helps optimize performance by reducing unnecessary re-renders, especially in large-scale applications.
- Better State Management for Predictability: With useReducer, state updates follow a predictable pattern where actions dictate the changes, making it easier to debug and manage state changes systematically.
When to Use useReducer
You should use useReducer when
- The state logic is complex and involves multiple sub-values or requires sophisticated updates.
- You need to manage state transitions in a predictable manner (such as when working with forms or handling multiple actions).
- You have multiple state variables that depend on each other and need to be updated together.
- The logic for updating the state is not just a simple assignment but involves computations, conditions, or complex updates.
useReducer vs useState
Both useReducer and useState manage state in React, but they serve different purposes:
- useState is used for simple state updates where you only need to store one value (e.g., numbers, strings).
- useReducer is used for more complex state logic, such as managing state transitions involving multiple sub-values.
While useReducer provides structure and clarity, it can be more complex and may add some overhead if used unnecessarily. Here are some performance considerations:
- Avoid overuse: If your state management is simple, useState might be more efficient. Use useReducer for complex or shared state logic.
- Optimal re-renders: Since useReducer uses a single state object and dispatches actions, it can help avoid unnecessary re-renders, making it more efficient in larger applications with complex interactions.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read