0
0
ReactDebug / FixBeginner · 4 min read

How to Handle Error State in React: Simple Guide

In React, handle error state by using 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.

jsx
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>
  );
}
Output
TypeError: Cannot read property 'name' of null
🔧

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.

jsx
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>
  );
}
Output
<div> <h1>User Profile</h1> <p>Name: John Doe</p> </div> // Or if error occurs: <div>Error: Network response was not ok</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.

Key Takeaways

Use React state to track error information separately from data.
Catch errors in async calls and update error state to inform users.
Render error messages conditionally to improve user experience.
Always check data existence before accessing its properties.
Use linting and best practices to prevent common error handling mistakes.