What is an error boundary?
- React course
- Intermediate
- Lesson 53/80
- 4 min
Learn the class component that catches errors in a subtree.
What is an error boundary?
If a component throws while rendering, React can crash the whole app. An error boundary is a special class component that catches errors in its descendants.
The boundary catches errors in the subtree with componentDidCatch or getDerivedStateFromError and switches to a fallback UI. Only the broken part is affected, not the whole app.
An error boundary can only be a class component; there is no hook equivalent. Even in modern React, classes are used for error catching.
Class component structure
An error boundary is a class component that holds state.hasError. getDerivedStateFromError updates the error state; componentDidCatch logs the error.
In render, if hasError is true the component returns the fallback UI, otherwise it returns children. This switches to the fallback automatically when an error occurs.
The two methods have different jobs: one updates state, the other performs side effects. Using both together is common.
Practice Error boundary skeleton
Complete the skeleton below. Write an ErrorBoundary class; extend Component, add a getDerivedStateFromError(error) method that returns {"{ hasError: true }"}, and a render method that returns <h1>Error</h1> if hasError is true, otherwise children. Export it.
Starter code
import { Component } from "react";
// Write the ErrorBoundary class hereSample solution
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) return <h1>Error</h1>;
return this.props.children;
}
}
export default ErrorBoundary;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which component type is an error boundary?
- Fonksiyon
- A class Correct answer
- Hook
- Memo
Explanation: An error boundary is a class component.
2 Error catching method
static getDerivedStateFromError(____) {
return { hasError: true };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
Explanation: getDerivedStateFromError(error) takes the error object.
3 What is an error boundary: match the terms
| Term | Meaning |
|---|---|
getDerivedStateFromError |
Updates state |
componentDidCatch |
Logs the error |
hasError |
Error state |
children |
Normal content |