Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
React Intermediate Free

Error Handling

Lesson 14 of 17 · Error Boundaries 82%
1. Getting Started
What is React?
2. Components & Props
Components & Props
6. Performance & Testing
React.memo & Lazy Loading
7. Custom Hooks
Building Custom Hooks
8. State Management
Context API Redux Basics
9. Error Boundaries
Error Handling
10. Server Components
React Server Components
11. Next.js Introduction
Next.js Basics
12. Animations & Transitions
Framer Motion

Error boundaries catch JavaScript errors anywhere in their child component tree.

Syntax

REACT
class ErrorBoundary extends React.Component {
    state = { hasError: false };
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    render() {
        if (this.state.hasError) return <h1>Something went wrong</h1>;
        return this.props.children;
    }
}
React Error Boundaries
REACT
import React, { Component } from "react";

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

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

    componentDidCatch(error, errorInfo) {
        console.error("Error:", error, errorInfo);
    }

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

        return this.props.children;
    }
}

function DangerousComponent() {
    throw new Error("Boom!");
    return <div>Never rendered</div>;
}

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

export default App;
Error Boundaries
REACT
import React from "react";

class ErrorBoundary extends React.Component {
    state = { hasError: false };

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

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

// A component that crashes while rendering
function BuggyComponent() {
    throw new Error("I crashed!");
}

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

Up next

React Server Components

Lesson 15 of 17 · Server Components