Sub topic 6
Getting event handler and async errors into a boundary
This chapter assumes you can write function components with hooks, you know how try/catch and async/await work, and you have read the earlier chapters on what boundaries catch. It covers how to send errors from event handlers and asynchronous code into a boundary when you want the boundary's fallback UI to appear.
Why these errors skip the boundary
An error boundary catches errors that React can see while it is rendering, in lifecycle methods, and in constructors of the tree below it. React can see them because it called your component function itself, inside its own render pass.
An event handler is different. React attaches it, but the browser calls it later, outside any render. If it throws, the error goes to the browser like any other uncaught exception. The same applies to code after an await, to setTimeout callbacks, and to Promise rejections. By the time they fail, React is no longer in the middle of rendering your component.
The result is that a thrown error in a click handler is logged to the console, and the UI stays exactly as it was. Nothing breaks visually, but the user gets no feedback that the action failed.
First choice: handle it where it happens
Most handler errors do not need a boundary. A failed save is usually an expected condition, and the right response is an inline message next to the button. Use try/catch and state:
import { useState } from "react";
function SaveButton({ save }) {
const [status, setStatus] = useState("idle");
const [message, setMessage] = useState("");
async function handleClick() {
setStatus("saving");
try {
await save();
setStatus("idle");
} catch (error) {
setMessage(error instanceof Error ? error.message : "Save failed");
setStatus("failed");
}
}
return (
<div>
<button onClick={handleClick} disabled={status === "saving"}>
{status === "saving" ? "Saving…" : "Save"}
</button>
{status === "failed" && <p role="alert">{message}</p>}
</div>
);
}Choose this approach when the user can fix the problem or retry on the spot, and when the rest of the screen is still usable.
When a boundary is the right target
Send the error to a boundary when the component can no longer show anything meaningful. Typical cases:
- A data fetch in an effect fails, and the component has nothing to display without that data.
- An unexpected error occurs that you did not plan for, and you want one consistent fallback plus central reporting.
- A feature is wrapped in a boundary that already offers a "Try again" button, and you want failures from handlers to use the same recovery path.
In these cases, you need a way to move the error from the non-React world back into a render, where a boundary can catch it.
The trick: rethrow during render
A boundary catches errors thrown during render. State updates can be given as functions, and React runs those functions during the next render. So you can store the error by throwing from inside a state updater:
import { useState } from "react";
function useThrowToBoundary() {
const [, setState] = useState();
return (error) => {
setState(() => {
throw error;
});
};
}When the returned function is called, React schedules a re-render of the component. During that render it runs the updater, which throws. The throw happens inside React's render, so the nearest boundary above the component catches it.
Here is the hook in use:
import { useEffect, useState } from "react";
function useThrowToBoundary() {
const [, setState] = useState();
return (error) => {
setState(() => {
throw error;
});
};
}
function Profile({ userId }) {
const [user, setUser] = useState(null);
const throwToBoundary = useThrowToBoundary();
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
setUser(await response.json());
} catch (error) {
if (error.name !== "AbortError") {
throwToBoundary(error);
}
}
}
load();
return () => controller.abort();
}, [userId]);
if (!user) return <p>Loading…</p>;
return <h2>{user.name}</h2>;
}Three details in this example matter:
fetchonly rejects on network failure. A 404 or 500 response resolves normally, so the code checksresponse.okand throws itself.- The cleanup function aborts the request when
userIdchanges or the component unmounts. An aborted request rejects with anAbortError, which is not a real failure, so the code ignores it. - Only the rethrow reaches the boundary. The
catchblock is still where you decide which errors deserve that treatment.
The flow looks like this:
The same thing with react-error-boundary
The react-error-boundary library ships this pattern as the useErrorBoundary hook. Its showBoundary function does what useThrowToBoundary does above, so you do not need to write your own hook if you already use the library:
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
async function save() {
const response = await fetch("/api/save", { method: "POST" });
if (!response.ok) {
throw new Error(`Save failed with status ${response.status}`);
}
}
function SaveButton() {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function Editor({ documentId }) {
return (
<ErrorBoundary FallbackComponent={Fallback} resetKeys={[documentId]}>
<SaveButton />
</ErrorBoundary>
);
}useErrorBoundary also returns resetBoundary, which clears the error from inside the subtree. The hook only works for components rendered under an ErrorBoundary from the library. Called outside one, it throws.
Common errors
The component unmounted before the error arrived
If the component is gone when the async work fails, the state update has no component to render, and the error never reaches a boundary. In React 18 and later this is silent. Two consequences follow:
- Do not rely on the boundary to report errors from work that outlives its component. Log them in the
catchblock too if you need a record. - Cancel work in the effect cleanup, as the
AbortControllerdoes above, so you do not process results nobody can see.
Calling the rethrow function during render
throwToBoundary(error) and showBoundary(error) are meant for callbacks, effects, and Promise handlers. If you call one directly in the component body, you trigger a state update during render. That is the same as throwing directly, only more confusing. If you can detect the error during render, throw it.
Swallowing errors with an empty catch
This code hides every failure:
try {
await save();
} catch (error) {
// nothing
}Every catch should do one of three things: show a message, rethrow to a boundary, or log and deliberately ignore a known harmless case.
Forgetting the Promise you did not await
A rejected Promise that nothing awaits becomes an unhandled rejection. A boundary never sees it. This happens often with a call like onClick={() => save()} where save is async but the handler does not wrap it in try/catch. Either handle the rejection inside save, or add .catch(showBoundary) at the call site.
Throwing values that are not errors
Some code throws strings or plain objects. A fallback that reads error.message then shows undefined. Normalize in your catch block:
const normalized = error instanceof Error ? error : new Error(String(error));
showBoundary(normalized);Errors in transitions
React 19 can also surface errors from an async function passed to startTransition, such as one from useTransition. An error thrown inside such an action is reported to the nearest error boundary, so you do not need a manual rethrow there. The same does not hold for ordinary onClick code or a bare fetch(...).then(...) chain. Check the React documentation for the version you run before relying on this.
Summary of the decision
| Situation | Approach |
|---|---|
| User can fix it and retry in place | `try/catch` plus local error state |
| Component cannot render without the result | Catch, then rethrow to the boundary |
| Failure inside an async transition action (React 19) | Let it reach the nearest boundary |
| Failure after the component has unmounted | Log in the `catch` block, the boundary will not see it |
Exercise
A click handler calls await save() inside try/catch, and the catch block calls console.error(error). The surrounding error boundary never shows its fallback. Why, and what is the smallest change that makes it show?
Show answer
Boundaries only catch errors thrown during rendering, and the handler runs outside a render, so catching and logging it never involves React. The smallest change is to call showBoundary(error) from useErrorBoundary (or a state updater that throws, such as setState(() => { throw error; })) inside the catch block. That causes a re-render in which the error is thrown, and the nearest boundary catches it.
Exercise
In an effect, you fetch data and call throwToBoundary(error) when the request fails. Users report that sometimes the fallback appears after they navigate away and back, showing an error from the earlier visit. What two changes in the effect prevent this?
Show answer
First, create an AbortController, pass its signal to fetch, and call controller.abort() in the effect cleanup, so the old request is cancelled when the dependency changes or the component unmounts. Second, ignore the resulting AbortError in the catch block (if (error.name !== "AbortError")), so a cancelled request is not reported as a failure.
Exercise
A fetch call returns a 500 response, but your catch block never runs. Why, and how do you fix it?
Show answer
fetch only rejects on network-level failures. A 500 response resolves normally with response.ok set to false. Check response.ok after the request and throw new Error(...) yourself, so the catch block runs and can route the error to a boundary.