React Error Boundaries
Catch JavaScript errors in components and show fallback UI.
Error Boundaries catch errors in component tree and show fallback UI.
Creating Error Boundary
```javascript 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:', error, errorInfo); }
render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; }
return this.props.children; } } ```
Using It
```javascript function App() { return ( <ErrorBoundary> <MyComponent /> </ErrorBoundary> ); } ```
Multiple Boundaries
```javascript <ErrorBoundary> <Header /> <ErrorBoundary> <Content /> </ErrorBoundary> <Footer /> </ErrorBoundary> ```
Remember
- Must be class component - Catches render errors - Shows fallback UI - Doesn't catch event handler errors
> Next: Learn API integration!