react-hooks/error-boundaries
Disallow JSX inside a try block, where catch cannot see rendering errors
Also called react_hooks/error-boundaries, react/error-boundaries
<Chart /> doesn't call Chart. It only describes what to render, and React calls the component later, after your function has returned. So if Chart throws while rendering, the try around the JSX is long over and its catch never runs.
To handle a rendering error, wrap the component in an error boundary.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react-hooks/error-boundaries" = "error" # or "warn"Examples#
example.jsx1 problem
function Dashboard({ data }) {
try {
return <Chart data={data} />Error: Avoid constructing JSX within try/catchReact does not immediately render components when JSX is rendered, so any errors from this component will not be caught by the try/catch. To catch errors in rendering a given component, wrap that component in an error boundary. (react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary).;
} catch {
return <p>Could not draw the chart.</p>;
}
}example.jsxNo problems
function Dashboard({ data }) {
return (
<ErrorBoundary fallback={<p>Could not draw the chart.</p>}>
<Chart data={data} />
</ErrorBoundary>
);
}A try around code that runs right away is fine, and so is JSX in the catch block:
example.jsxNo problems
function Dashboard({ json }) {
let data;
try {
data = JSON.parse(json);
} catch {
return <p>Could not read the data.</p>;
}
return <Chart data={data} />;
}