Handling Error using React useState and useEffect Hooks
Last Updated :
24 Apr, 2025
In React, handling error states is very important to provide a smooth user experience and handle unexpected errors that may occur during data fetching or asynchronous operations. By using the useState and useEffect hooks, you can easily manage error states in your React applications.
In this article, we'll explore how to handle error states using the useState
and useEffect
hooks in React.
What are Error States?
Error states represent situations where something unexpected happens in an application. These errors commonly occur during asynchronous operations such as fetching data from an API, processing user input, or rendering components. Common reasons of errors include network failures, server errors, and unexpected data formats.
Using useState and useEffect Hooks
React provides the useState
and useEffect
hooks, which are fundamental for managing state and side effects in functional components. These hooks helps us to handle error states efficiently by updating component state in response to errors and triggering error-related side effects.
Approach to handle Error States:
To use useState and useEffect , import it from the react library at the top of your component file:
import React, { useState,useEffect } from 'react';
Within your functional component, call useState with the initial state value as an argument. It returns an array containing two elements:
- The Current state value: Use this in your JSX to display the data dynamically.
- A State update function: Call this function to modify the state and trigger a re-render of the component.
React useState Hook Syntax:
const [error, setError] = useState(null);
The useEffect hook syntax accepts two arguments where the second argument is optional
React useEffect Hook Syntax:
useEffect(<FUNCTION>, <DEPENDECY>)
- FUNCTION: contains the code to be executed when useEffect triggers.
- DEPENDENCY: is an optional parameter, useEffect triggers when the given dependency is changed.
Steps to Create React App and handle Errors:
Step 1: Create a react application using the following command.
npx create-react-application my-react-application
Step 2: Navigate to the root directory of your application using the following command.
cd my-react-application
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example:In case of an error, it will render an error message with details. Once data is successfully fetched, it will render the fetched data or UI components accordingly.
JavaScript
// App.js
import React, { useState, useEffect } from 'react';
const ErrorHandling = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchData()
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []);
const fetchData = async () => {
try {
// Simulate an API call
const response = await fetch
('https://jsonplaceholder.typicode.com/post');
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return response.json();
} catch (error) {
throw new Error('Failed to fetch data');
}
};
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (!data) {
return <div>No data available</div>;
}
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
};
export default ErrorHandling;
Output:
OutPut for Error State- If Request is Succeed then list of data is shown:
OutPut if request succeeds
Similar Reads
Difference Between useState and useEffect Hook in ReactJS
ReactJS is the powerful JavaScript library used for building user interfaces especially single-page applications(SPAs). Two of the most commonly used hooks in React are useState and useEffect. These hooks make functional components more powerful by allowing them to manage the state and handle side e
3 min read
Difference Between useEffect and useLayoutEffect Hook in ReactJS
In this article, we will learn about the differences between useEffect and useLayoutEffect in React with the help of an example. We will create a counter and implement it using both useEffect and useLayoutEffect to understand the differences practically. useEffectThe useEffect is used to perform sid
5 min read
Fetching Data from an API with useEffect and useState Hook
In modern web development, integrating APIs to fetch data is a common task. In React applications, the useEffect and useState hooks provide powerful tools for managing asynchronous data fetching. Combining these hooks enables fetching data from APIs efficiently. This article explores how to effectiv
4 min read
Animation and Transitions using React Hooks
Animations allows to control the elements by changing their motions or display. Animation is a technique to change the appearance and behaviour of various elements in web pages. Transitions in CSS allow us to control the way in which transition takes place between the two states of the element. We c
6 min read
How To Avoid Infinite Loops When Using useEffect() in ReactJS?
useEffect() can lead to infinite loops, causing performance issues or crashes if not used correctly. In this article, we will explain what causes these infinite loops and how to avoid them when working with useEffect() in ReactJS.Avoid infinite loops in useEffect() by providing appropriate dependenc
4 min read
How to handle input forms with useState Hook in React ?
Handling input forms with useState in React involves creating state variables to store the values of input fields and updating them as the user interacts with the form. Handling input forms with useState:State Variables: Define state variables to hold the values of input fields. Each input field typ
2 min read
Form Handling with React Hooks
Forms are an important part of web development. Form handling is a crucial user interaction for websites. React hooks provide a concise and very efficient way to handle the state of the form as the user interacts with the form fields. There are mainly two react hooks for this purpose. useState:- use
4 min read
Can you explain what the useState hook does in React Hooks?
The useState hook is a feature in React Hooks that allows you to add state to functional components. It creates state variables and manages their values within a functional component. Why is useState important?Before introducing hooks in React, state management was only possible in class components.
2 min read
Hook error handling doesn't catch errors in ReactJS
In this article, we will see one of the common issues faced by ReactJS developers is the Hook error handling problem. This issue occurs when an error is thrown inside a Hook, but it is not caught and handled properly. As a result, the error goes unaddressed and can cause unexpected behavior in the a
2 min read
How to log-out user from app using ReactJS ?
The objective of this article is to how we can set up, log out a user, and retrieve data from local memory User Browser storage in the React app. During the sign-in session, we will save the user details to the browser's local storage, and also during the time of logout, we will remove the user's de
3 min read