Sub topic 1
What happens when a component throws while rendering
When a component throws an error during rendering, React has to decide what to do with the half-built UI. This chapter explains what React does by default, why it does that, and which errors this applies to. Later chapters build error boundaries on this foundation, so the goal here is a precise mental model of the failure.
Prerequisites
This chapter assumes you have:
- Working knowledge of React function components and JSX.
- Familiarity with props, state, and the component lifecycle.
- Basic JavaScript error handling with
throwandtry/catch. - A basic understanding of Promises and
async/await.
The examples use React 18 or 19 with createRoot. Where the behavior differs between versions, the text says so.
What "rendering" means here
In React, rendering is the act of calling your component functions to work out what the UI should look like. React calls each component with its props, collects the JSX it returns, and builds a tree of elements. Only after that does it update the DOM, in a separate step called the commit phase.
This split matters for errors. A rendering error happens while React is still calculating. Nothing has been committed yet, so React has no complete, consistent description of the UI to show.
The following things all run during rendering, and any of them can throw:
- The body of a function component.
- The
rendermethod of a class component. - Constructors and lifecycle methods such as
getDerivedStateFromProps. - Hooks called inside a component, including the initializer function you pass to
useStateand the function passed touseMemo. - Code that components call, such as helpers that format data or read from context.
A component that throws
Here is a small app where one component fails because of bad data.
import { createRoot } from "react-dom/client";
function Profile({ user }) {
// Throws a TypeError when user is null:
// "Cannot read properties of null (reading 'name')"
return <h2>{user.name}</h2>;
}
function App() {
return (
<main>
<h1>My app</h1>
<nav>Home | Settings</nav>
<Profile user={null} />
</main>
);
}
createRoot(document.getElementById("root")).render(<App />);Profile is only one small piece of the page. The heading and the navigation are fine. Even so, you will not see them. The page goes blank.
Why the whole tree disappears
When a component throws during rendering and no error boundary is above it, React unmounts the whole component tree under the root. "Unmount" means React removes the components and their DOM nodes. The container element, #root in the example, is left empty.
React does this deliberately. The reasoning goes like this:
- A component failed, so React cannot produce the output that component was supposed to produce.
- The rest of the tree may depend on that output, directly or through state, context, or the layout of the page.
- Showing a partial UI could mislead the user. A payment page that renders everything except an error message, or a settings form that shows stale values, can lead users to take wrong actions.
- Leaving a corrupted UI on screen is considered worse than showing nothing.
React's position is that a broken UI is worse than an absent one. This was a design decision made in React 16. Before that, errors thrown during rendering left React's internal state inconsistent. Later renders then failed with confusing, unrelated errors, and the visible UI could drift out of sync with the real state. Unmounting the tree puts React back in a known state.
The sequence of events
The following diagram shows what happens between the throw and the blank page.
The branch on the right of the diagram is the subject of the next chapters. This chapter is about the left branch, which is what you get by default.
What you see in the browser
In development mode, you usually see two things:
- A full-screen error overlay, if your tooling provides one. Tools such as Vite, Next.js, and Create React App add this. The overlay is not React itself, and you can dismiss it.
- The error and a component stack in the browser console.
After you dismiss the overlay, the page behind it is blank. In production there is no overlay. Users see an empty page, and the only evidence is in the console, if anyone ever opens it.
A component stack is a list of the components that were being rendered when the error occurred, from the failing component upward. For the example above it looks roughly like this:
at Profile (App.jsx:4)
at main
at App (App.jsx:9)This is more useful than a JavaScript stack trace alone. A JavaScript stack shows functions called, which in a React app are often internal React functions. The component stack shows your component hierarchy. Later chapters show how to capture it for logging.
Which errors count as rendering errors
Not every error in a React app is a rendering error. The category matters because it decides whether the tree unmounts.
| Where the error is thrown | Rendering error? | Effect on the tree |
|---|---|---|
| Component body or `render` method | Yes | Unmounts the tree if no boundary catches it |
| `useState` initializer, `useMemo` callback | Yes | Same |
| Class constructor or lifecycle method | Yes | Same |
| Inside `useEffect` or `useLayoutEffect` | Treated as a rendering failure by React | Same |
| Event handler such as `onClick` | No | The tree stays mounted |
| `setTimeout` callback | No | The tree stays mounted |
| Code after `await`, or a rejected Promise | No | The tree stays mounted |
Two rows deserve extra explanation.
Effects run after the commit, not during rendering itself. React still treats an error thrown from an effect as a failure of the component, because the component's side effects did not complete. In practice it unmounts the tree the same way, and an error boundary can catch it.
Event handlers, timers, and async code run outside React's render. React did not call them as part of building the tree, so a failure there does not tell React that the UI is invalid. The error goes to the browser as an ordinary uncaught error or unhandled rejection. The UI stays on screen, possibly in a half-updated state that you must manage yourself. A later chapter covers this group in detail.
Why try/catch inside JSX does not help
A common first idea is to wrap the component in try/catch.
function App() {
try {
return (
<main>
<Profile user={null} />
</main>
);
} catch (error) {
return <p>Something went wrong.</p>;
}
}This does not work. <Profile user={null} /> does not call Profile. JSX only creates an element, which is a plain object describing what to render. React calls Profile later, from its own rendering code, after App has already returned. By then the try block is long finished, so the catch never runs.
You can use try/catch inside a component for code the component itself executes, such as parsing a value:
function Price({ raw }) {
let value;
try {
value = JSON.parse(raw);
} catch {
value = null;
}
if (value === null) {
return <span>Price unavailable</span>;
}
return <span>{value.amount}</span>;
}Here the component runs JSON.parse directly, so try/catch works. This is the right tool for errors you expect and can handle locally. It cannot protect you from failures in child components, because React runs those, not you.
Strict Mode and double rendering
In development, StrictMode renders each component twice to help find impurities. If a component throws, you may see the error reported twice in the console. This is expected and does not happen in production. Do not treat the duplicate log as two separate bugs.
React 19 also changes how errors are logged. It reports each error once, with a combined message and component stack, instead of several repeated messages. Which messages you see therefore depends on your React version.
Rendering errors can be caused by data, not only by bugs
Developers often assume a rendering error means a coding mistake. In real applications many are caused by conditions that you cannot fully control:
- An API returns
nullor a field with a different shape than expected. - A third-party widget throws on unusual input.
- A user's locale makes a formatting call throw, for example
Intlwith an invalid option. - A feature flag enables a component that depends on data not yet loaded.
- A code-split chunk fails to download, so a lazy component throws when React tries to load it.
Because these can occur in production after your tests passed, you want a way to contain the damage rather than rely on never having a bug. That is the job of an error boundary.
Edge cases to keep in mind
- Throwing non-errors. JavaScript lets you
throwany value, including strings or objects. React handles these, but you lose the stack trace and themessageproperty. ThrowErrorobjects. - Errors during the first render. If the very first render of the root throws and there is no boundary, the container stays empty. There is no earlier UI to fall back to.
- Errors during updates. If the app rendered fine and a later update throws, for example after a state change, the already visible UI is removed. Users see a working page turn blank.
- State is lost. Unmounting discards all component state in the removed tree. Text typed into a form, scroll positions held in state, and open menus are gone. Reloading the page is the only recovery without a boundary.
- The error is not swallowed. React rethrows the error so that it appears in the console and in global error handlers such as
window.onerrorin browsers. Monitoring tools that hook into that often report it, but without the component stack.
Reproducing the failure yourself
You can see the behavior with a small component that throws on demand.
import { useState } from "react";
import { createRoot } from "react-dom/client";
function Bomb({ explode }) {
if (explode) {
throw new Error("Bomb exploded during render");
}
return <p>All quiet.</p>;
}
function App() {
const [explode, setExplode] = useState(false);
return (
<main>
<h1>Render error demo</h1>
<button onClick={() => setExplode(true)}>Explode</button>
<Bomb explode={explode} />
</main>
);
}
createRoot(document.getElementById("root")).render(<App />);Click the button. The state update triggers a render, Bomb throws, and the heading, the button, and the paragraph all vanish. Now compare this with moving the throw into the click handler:
<button
onClick={() => {
throw new Error("Thrown in an event handler");
}}
>
Explode
</button>The error appears in the console, but the page stays on screen. This contrast is the key to the rest of the tutorial. Rendering errors remove the tree. Errors elsewhere do not.
Exercise
A component throws inside a setTimeout callback that it started from a useEffect. Does React unmount the tree? Then say what happens if the same component throws in its function body during a render, and no error boundary exists.
Show answer
A throw inside a setTimeout callback does not unmount the tree. The callback runs outside React's render, so the browser reports an ordinary uncaught error and the UI stays on screen. A throw in the function body is a rendering error. With no error boundary above it, React unmounts the whole tree under the root and leaves the container empty.
Exercise
Why does wrapping <Profile user={null} /> in a try/catch inside App fail to catch the error that Profile throws?
Show answer
JSX only creates an element object and does not call Profile. React calls Profile later, after App has returned and its try block has finished. The catch block therefore never sees the error.