Engineering note · React Js

How to Use Error Boundaries to Handle Errors

Error Boundaries are essential for building stable React applications by catching and managing unexpected errors.

By Published

React Js

1. Define an ErrorBoundary class component

CODE SAMPLE Code snippet
class ErrorBoundary extends React.Component {
    // initiate component
}

2. State Initialization in Constructor

The constructor initializes the component's state with hasError: false, indicating that, by default, no error has occurred.

CODE SAMPLE Code snippet
constructor(props) {
    super(props);
    this.state = { hasError: false };
}

3. Static Method getDerivedStateFromError

This static method is called by React whenever a child component throws an error. It updates the component’s state to hasError: true, signaling that an error has been caught.

Setting hasError to true triggers a re-render, allowing us to show a fallback UI.

CODE SAMPLE Code snippet
static getDerivedStateFromError() {
    return { hasError: true };
}

4. Render the state

CODE SAMPLE Code snippet
render() {
    if (this.state.hasError) {
        return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
}

In the render method, a check is made on this.state.hasError.

If an error is detected (hasError is true), the component displays a fallback UI with the message “Something went wrong.”

If no error is detected, it renders the component’s children (i.e., the components wrapped by ErrorBoundary).

5. Usage

CODE SAMPLE Code snippet
<ErrorBoundary>
    <MyComponent />
</ErrorBoundary>

With this setup, if MyComponent or any of its children throw an error, the ErrorBoundary will catch it and display the fallback UI.

More engineering notes

Conditional Rendering with Short Circuit

if you don’t need the else block while rendering components in React Js, you can do like this ```...

Labels: Names used to label loops and control flow

Labels in Node.js (and JavaScript) are used to name a statement, typically for controlling the flow...