Error boundaries in React are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. Error boundaries cannot catch errors inside themselves, in asynchronous code, or in event handlers.
How to create error boundaries:
- Create a class component that implements the
componentDidCatch
andgetDerivedStateFromError
methods:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
- Wrap the components that may generate errors with the error boundary:
<ErrorBoundary> <MyComponent /> </ErrorBoundary>
Error boundaries are essential for ensuring that errors in child components do not crash the entire application.