React › Error Boundaries
Why does React not catch errors that happen inside event handlers, like an onClick function, using error boundaries?
IntermediateAnswer
Error boundaries only catch errors that happen while React is rendering, updating lifecycle methods, or during construction. An error thrown inside an event handler happens outside of that rendering process, so it does not crash the component tree the same way, and needs to be handled with a regular try catch block instead.
function DeleteButton({ id }) {
function handleClick() {
try {
deleteItem(id);
} catch (error) {
console.error('Failed to delete item', error);
alert('Something went wrong while deleting');
}
}
return <button onClick={handleClick}>Delete</button>;
}Real-world example A delete button wraps its click handler logic in a regular try catch block, since an error boundary placed around the button would not actually catch an error thrown directly inside that click function.