Error boundaries catch JavaScript errors anywhere in their child component tree.
Getting Started
What is React?
Components & Props
Components & Props
Performance & Testing
React.memo & Lazy Loading
Custom Hooks
Building Custom Hooks
Error Boundaries
Error Handling
Server Components
React Server Components
Next.js Introduction
Next.js Basics
Animations & Transitions
Framer Motion
React
Intermediate
FREE
Error Handling
Lesson 1 of 17
Intermediate
Interactive
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; } } function App() { return ( <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> ); }