Error Handling in React

Introduction

As applications grow, errors are unavoidable. A small bug in one component can sometimes break the entire user interface. To prevent the whole app from crashing and to provide a better user experience, React offers mechanisms for handling errors gracefully.

In this chapter, you will learn how React manages errors and how to display fallback UI when something goes wrong.

What Are Errors in React?

Errors in React can occur due to:

  • Bugs in component code

  • Failed API calls

  • Unexpected user input

  • Rendering issues

Without proper handling, these errors can stop the application from working correctly.

Error Boundaries in React

Error Boundaries are special components that catch JavaScript errors in their child component tree. They log the error and display a fallback UI instead of crashing the whole app.

Error Boundaries work only in class components.

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.log("Error caught:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }

    return this.props.children;
  }
}

Wrap components with ErrorBoundary to protect them.

Using an Error Boundary

function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}

If BuggyComponent throws an error, the fallback message is shown.

Handling Errors in Functional Components

Functional components do not directly support error boundaries, but they can be wrapped with one. You can also handle specific errors using try/catch blocks in event handlers or async functions.

function FetchData() {
  async function getData() {
    try {
      const res = await fetch("/api/data");
      const data = await res.json();
      console.log(data);
    } catch (error) {
      console.log("Fetch error:", error);
    }
  }

  return <button onClick={getData}>Load Data</button>;
}

Showing User-Friendly Error Messages

Instead of logging errors only, show helpful messages to users.

function Form() {
  const [error, setError] = useState(null);

  function handleSubmit() {
    try {
      throw new Error("Invalid input");
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div>
      {error && <p>{error}</p>}
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}

Best Practices for Error Handling

  • Use Error Boundaries for UI-level errors

  • Handle API errors with try/catch

  • Show meaningful messages to users

  • Log errors for debugging

Summary

In this chapter, you learned how to manage errors in React applications using Error Boundaries and try/catch blocks. You saw how to prevent app crashes, display fallback UI, and provide user-friendly messages. Proper error handling improves application reliability and user experience.