Mark As Completed Discussion

Other Lifecycle Methods

In addition to the constructor, mounting, updating, and unmounting methods, React components also provide various additional lifecycle methods that you can use to perform specific tasks at different stages of a component's lifecycle.

One of these additional methods is componentDidCatch(error, info). This method is invoked when an error occurs during rendering, in a lifecycle method, or in the constructor of any child component. It allows you to catch and handle these errors properly.

Here's an example that demonstrates the usage of the componentDidCatch() method:

JAVASCRIPT
1// Example of a custom lifecycle method
2
3class ErrorBoundary extends React.Component {
4  constructor(props) {
5    super(props);
6    this.state = {
7      hasError: false
8    };
9  }
10
11  componentDidCatch(error, info) {
12    // Update state to display an error message
13    this.setState({ hasError: true });
14    // Log the error and component stack trace
15    console.error(error);
16    console.log(info.componentStack);
17  }
18
19  render() {
20    if (this.state.hasError) {
21      // Render an error message
22      return <h1>Something went wrong.</h1>;
23    }
24
25    // Render the component's children
26    return this.props.children;
27  }
28}
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment