Error Boundaries

Amol Gunjal
2 min readJul 2, 2021

React 16 introduces a new concept of an “error boundary”

Error boundaries are React 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.

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods
static getDerivedStateFromError() or componentDidCatch().

Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown.
Use componentDidCatch() to log error information.

Example:

import React from 'react';class ErrorBoundary extends React.Component {

constructor( props ) {
super( props );
this.state = { hasError: false, error: null, errorInfo: null };
}
componentDidCatch( error, errorInfo ) {
this.setState({
hasError: true,
error: error,
errorInfo: errorInfo
})
}
render() {
if( this.state.hasError ) {
return (
<div>
<h1> Something went wrong...</h1>;
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;

Then you can use it as a regular component:

<ErrorBoundary>
<Suspense fallback={<div>Please wait...</div>}>
<Home />
<About />
</Suspense>
</ErrorBoundary>

Only class components can be error boundaries.

Note that error boundaries only catch errors in the components below them in the tree.
An error boundary can’t catch an error within itself.

If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it.
This, too, is similar to how catch {} block works in JavaScript.

Another example for reference.

--

--