> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks)
> * Server Side Rendering
> * Server side rendering
> * Errors thrown in the error boundary itself (rather than its children)
A class component becomes an error boundary if it defines a new lifecycle method called `componentDidCatch(error, info)`:
@ -136,34 +138,39 @@ However, React components are declarative and specify *what* should be rendered:
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` hook caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
However, an event handler inside of a React component could leverage `try` / `catch` to deal with errors that occur during event handling.
React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle hooks, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:
```js{8-12,16-19}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { error: null }
this.state = { error: null };
}
handleClick = () => {
try {
// event handling that could possibly produces an error
// Do something that could throw
} catch (error) {
this.setState({ error })
this.setState({ error });
}
}
render() {
if (this.state.error) {
// render a fallback UI
return <h1>The Click Handler Produces an Error</h1>