javascript / intermediate
Snippet
React Error Boundaries
Error Boundaries are class components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ErrorBoundary extends React.Component {constructor(props) {super(props);this.state = { hasError: false };}static getDerivedStateFromError(error) {return { hasError: true };}componentDidCatch(error, info) {console.error('Error caught:', error, info);}render() {if (this.state.hasError) {return <h1>Something went wrong.</h1>;}return this.props.children;}}
react
Breakdown
1
static getDerivedStateFromError(error)
This lifecycle method updates the state so the next render will show the fallback UI after an error occurs.
2
componentDidCatch(error, info)
This method is used to log error information to an error reporting service or the console.