Why do not you need error boundaries for event handlers?

Error boundaries do not catch errors inside event handlers. Event handlers don't happened or invoked during rendering time unlike render method or lifecycle methods. So React knows how to recover these kind of errors in event handlers. If still you need to catch an error inside event handler, use the regular JavaScript try / catch statement as below

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
handleClick = () => {
try {
// Do something that could throw
} catch (error) {
this.setState({ error });
}
};
render() {
if (this.state.error) {
return <h1>Caught an error.</h1>;
}
return <div onClick={this.handleClick}>Click Me</div>;
}
}

The above code is catching the error using vanilla javascript try/catch block instead of error boundaries.


June 19, 2022
124