Error Trapping in React: How to Use Error Boundaries?
🎯 What Will You Learn in This Guide?
This guide walks you through the Error Boundaries structure used to prevent unexpected crashes in your React applications.
You will learn to catch errors, display a fallback UI to the user, and log errors using the getDerivedStateFromError and componentDidCatch lifecycle methods.
🚧 Prerequisites
- Basic React knowledge
- A development environment with Node.js and npm installed
- This guide has been tested with Node v16+, npm v7+, React v17+
1️⃣ Error Scenario Without Error Limit
Prior to React v16 or without Error Boundary, errors occurring during the rendering phase would cause the entire application to crash.
The user sees a blank page (white screen) and does not understand what is happening.
The following example simulates this situation:
import React from 'react';
class BuggyCounter extends React.Component {
state = { counter: 0 };
handleClick = () => {
this.setState({ counter: this.state.counter + 1 });
};
render() {
if (this.state.counter === 5) {
// Hata simülasyonu!
throw new Error('Simulated error.');
}
return (
<div>
<h1>{this.state.counter}</h1>
<button onClick={this.handleClick}>+</button>
</div>
);
}
}
export default BuggyCounter;
When the counter reaches 5, an error is thrown and the application is completely unmounted.
As a result, the user sees a white screen. But if we use Error Boundaries, we can catch the error before the application crashes.
2️⃣ What is Error Boundary?
Error Boundaries are structures that allow us to catch errors that occur in the rendering, lifecycle or constructor phase of React components. This means we can catch the error before the application crashes and show a special message to the user.
A component is considered Error Boundary if it contains one of these two methods:
static getDerivedStateFromError(error) → Catches the error and updates the state, triggering a “fallback UI”.
componentDidCatch(error, info) → Logs error details or reports them to external services.
3️⃣ Let's Create Our Own Error Boundary Component
The following class-based component catches errors occurring in child components:
import React from 'react';
class HataSiniri extends React.Component {
state = { errorMessage: '' };
static getDerivedStateFromError(error) {
// Hata durumunu güncelliyoruz
return { errorMessage: error.toString() };
}
componentDidCatch(error, info) {
// Hata detaylarını logluyoruz
this.logError(error.toString(), info.componentStack);
}
logError = console.log; // Örnek log fonksiyonu
render() {
if (this.state.errorMessage) {
return <p>Hata oluştu: {this.state.errorMessage}</p>;
}
return this.props.children;
}
}
export default HataSiniri;
This class shows a special message to the user when an error occurs in the subcomponents within it.
4️⃣ Integrating Error Boundary into the Application
Let's now enclose our BuggyCounter component in ErrorBound:
import React from 'react';
import BuggyCounter from './BuggyCounter';
import HataSiniri from './HataSiniri';
class App extends React.Component {
refreshPage = () => window.location.reload();
render() {
return (
<div>
<HataSiniri>
<BuggyCounter />
</HataSiniri>
<hr />
<button onClick={this.refreshPage}>Sayfayı Yenile</button>
</div>
);
}
}
export default App;
Now when the counter reaches 5, the application does not crash, only the faulty component shows the message “An error occurred”.
5️⃣ Difference Between Error Boundaries and Try...Catch
These two are not alternatives to each other, but complements. Error Bounds only catch errors specific to React components.
| ✅ Situations Capable of Capturing | ❌ Situations He Couldn't Catch |
|---|---|
| Errors occurring during the rendering phase | Event handler (e.g. onClick, onChange) errors |
In lifecycle methods (componentDidMount, componentDidUpdate etc.) | Errors in setTimeout or requestAnimationFrame |
| In the constructor phase | Errors during server-side rendering (SSR) |
| Errors occurring within the error boundary itself |
For robust error handling, both Error Boundary and try...catch should be used.
💬 Frequently Asked Questions (FAQ)
- Does Error Boundaries only work on class components?
Yes. Error Boundary cannot be written directly with hooks. Class-based components and lifecycle methods are required.
- Should I wrap my entire application with a single Error Boundary?
Usually having one in the root component is sufficient. But local Error Limits are also recommended for critical areas.
- How customizable is Fallback UI?
As many as you want! It can be simple text, a button, or a custom error page.
- Where should I send error logs?
You can send it to services such as Sentry and Crashlytics in componentDidCatch.
- Why is it important for user experience?
Your app looks professional by displaying a controlled error screen without crashing.
🏁 Result
Error Boundaries, introduced with React 16, prevents your application from crashing and provides the user with a controlled error screen. Thanks to this structure, the user sees a clear message instead of a white screen.
Whether your application is small or a large project running on GenixNode, it is recommended to have an Error Boundary in the root component.
🚀 Try it in your own project now and take your user experience to the next level!

