Validates usage of Error Boundaries instead of try/catch for errors in child components.
Rule Details
Try/catch blocks can’t catch errors that happen during React’s rendering process. Errors thrown in rendering methods or hooks bubble up through the component tree. OnlyError Boundaries can catch these errors.
Invalid
Examples of incorrect code for this rule:
// ❌ Try/catch won't catch render errors
functionParent(){
try{
return<ChildComponent/>;// If this throws, catch won't help
}catch(error){
return<div>Error occurred</div>;
}
}Valid
Examples of correct code for this rule:
// ✅ Using error boundary
functionParent(){
return(
<ErrorBoundary>
<ChildComponent/>
</ErrorBoundary>
);
}Troubleshooting
Why is the linter telling me not to wrapuse intry/catch?
Theuse hook doesn’t throw errors in the traditional sense, it suspends component execution. Whenuse encounters a pending promise, it suspends the component and lets React show a fallback. Only Suspense and Error Boundaries can handle these cases. The linter warns againsttry/catch arounduse to prevent confusion as thecatch block would never run.
// ❌ Try/catch around `use` hook
functionComponent({promise}){
try{
constdata =use(promise);// Won't catch - `use` suspends, not throws
return<div>{data}</div>;
}catch(error){
return<div>Failed to load</div>;// Unreachable
}
}
// ✅ Error boundary catches `use` errors
functionApp(){
return(
<ErrorBoundaryfallback={<div>Failed to load</div>}>
<Suspensefallback={<div>Loading...</div>}>
<DataComponentpromise={fetchData()}/>
</Suspense>
</ErrorBoundary>
);
}