How to Handle Error State in React: Simple Guide
useState to track errors and conditionally render error messages in your component. This lets you show friendly feedback when something goes wrong, improving user experience.Why This Happens
When you fetch data or perform actions in React, errors can happen, like network failures or invalid input. If you don't track these errors, your app might crash or show nothing, confusing users.
import React, { useState, useEffect } from 'react'; function UserProfile() { const [user, setUser] = useState(null); useEffect(() => { fetch('https://api.example.com/user') .then(response => response.json()) .then(data => setUser(data)); }, []); return ( <div> <h1>User Profile</h1> <p>Name: {user && user.name}</p> </div> ); }
The Fix
Use useState to add an error state. Catch errors during fetch and update this state. Then, conditionally render an error message if an error exists, or the data if it loads successfully.
import React, { useState, useEffect } from 'react'; function UserProfile() { const [user, setUser] = useState(null); const [error, setError] = useState(null); useEffect(() => { fetch('https://api.example.com/user') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => setUser(data)) .catch(err => setError(err.message)); }, []); if (error) { return <div>Error: {error}</div>; } if (!user) { return <div>Loading...</div>; } return ( <div> <h1>User Profile</h1> <p>Name: {user.name}</p> </div> ); }
Prevention
Always anticipate errors when fetching data or performing async tasks. Use try/catch or .catch() to handle errors. Keep error state separate from data state. Use clear messages for users and consider retry options. Use linting tools like ESLint with React plugins to catch common mistakes early.
Related Errors
Common related errors include unhandled promise rejections, accessing properties of null or undefined, and forgetting to check loading states. Fix these by always checking if data exists before rendering and handling promises properly.