Error Boundaries — catch JavaScript errors in component tree.
1class ErrorBoundary extends React.Component {2 state = { hasError: false, error: null };34 static getDerivedStateFromError(error) {5 return { hasError: true, error };6 }78 componentDidCatch(error, errorInfo) {9 logErrorToService(error, errorInfo);10 }1112 render() {13 if (this.state.hasError) {14 return <ErrorFallback error={this.state.error} />;15 }16 return this.props.children;17 }18}
Usage:
1<ErrorBoundary>2 <App />3</ErrorBoundary>
Limitations: