Handling Errors in React
Errors happen, even in production. Error boundaries let you replace the "white screen of sadness" with a clear, friendly message, and keep the rest of the app working.

When you work on applications, errors and bugs are a fact of life, even in production. Whatever the issue, it's crucial to tell your users about it clearly and kindly, in a well-designed interface.
This is an important part of building user-friendly React applications. You can't predict or prevent every error, but you can control how they're handled.
There are various kinds of errors in JavaScript, for example:
- Syntax errors: mistakes in the structure of your code, such as typos, mismatched parentheses or brackets. These usually stop your build (or your editor flags them) before the code ever reaches users.
- Reference errors: using variables or functions that haven't been defined.
- Type errors: an operation performed on a value of the wrong type, like calling
user.name.toUpperCase()whenuserisundefined.
When a reference or type error is thrown while React is rendering, and nothing handles it, React removes the whole tree from the page. You or your users get the white screen of sadness 😕:
This is, of course, a terrible user experience. We want to tell our users what's happening when something goes wrong, and ideally let them carry on with the rest of the app.
Error boundaries
An error boundary is a special component that catches errors thrown while rendering the components inside it, and shows a fallback UI instead. For a component to work as an error boundary:
- It must be a class component. (There's still no hook for this.)
- It must implement
static getDerivedStateFromErrorand/orcomponentDidCatch.
A basic error boundary looks something like this:
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
// Update state so the next render shows the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// Extra logic, like logging the error to an error reporting service.
logErrorToSomeService(error, info.componentStack);
}
render() {
if (this.state.hasError) {
// Shown whenever a component inside throws.
return this.props.fallback;
}
return this.props.children;
}
}You can then wrap part of your component tree with it:
<ErrorBoundary fallback={<p>Something went wrong</p>}>
<UserDetails />
</ErrorBoundary>If UserDetails, or any of its children, throws an error while rendering, ErrorBoundary "catches" it, reports it to your error reporting service and displays the fallback passed in the fallback prop. Everything outside the boundary keeps working.
Fortunately, you don't need to write and maintain all of this yourself: the react-error-boundary (opens in a new tab) package gives you everything you need to manage runtime errors declaratively, including a way to reset the boundary and try again.
import { ErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
<ErrorBoundary FallbackComponent={Fallback} onError={logErrorToSomeService}>
<UserDetails />
</ErrorBoundary>;Not all errors are caught 🤦🏾♂️
Unfortunately, there are some errors that React does not pass to error boundaries:
- errors in event handlers, such as
onClickoronSubmit; - asynchronous code, such as
setTimeoutorrequestAnimationFramecallbacks and promises; - server-side rendering;
- errors thrown in the error boundary itself, rather than in its children.
react-error-boundary has a useErrorBoundary hook that returns a showBoundary function. Calling it sends an error to the nearest error boundary, which makes it useful for exactly these cases. For example:
import { useState } from "react";
import { useErrorBoundary } from "react-error-boundary";
function UserDetails() {
const [user, setUser] = useState({ address: "", age: "" });
const { showBoundary } = useErrorBoundary();
function handleSubmit(event) {
event.preventDefault();
const name = event.target.elements.name.value;
fetchUser(name).then(
(data) => setUser({ address: data.address, age: data.age }),
(error) => showBoundary(error),
);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input id="name" />
<button type="submit">Get user details</button>
</form>
);
}When the fetchUser promise is rejected, showBoundary is called with the error, and react-error-boundary passes it on to the closest error boundary.
Where to place error boundaries
You don't need to wrap every component in its own error boundary, but:
- Think about where it makes sense to show an error message, and what the user can still do from there.
- Wrap your entire application in an error boundary. That way, any error is caught and handled in a user-friendly way, wherever it happens.
- Wrap components that depend on data from an external source, such as an API, in their own boundary, so one failing widget doesn't replace the whole page.
Conclusion
Good error handling is essential to give users a good experience of your application. By understanding the different kinds of errors and putting the right boundaries in place, you can make your React applications more reliable and much friendlier when things go wrong.
The react-error-boundary package is an amazing tool to help you manage errors more effectively. Thanks for reading, and good luck!
Geologist turned frontend engineer from Cameroon, based in Ghana. Makes web and mobile apps faster and writes down how. More about me

