- Animation
- Bootstrap
- Button
- Components
- Conditional rendering
- Context API
- Debounce
- Error boundary
- Events
- Form
- Fragment
- Hooks
- Inline styling
- Key
- Lazy loading
- Lifecycle methods
- Portal
- Prop types
- Props
- Redux library
- Ref
- Router
- State
- State management
- Strict mode
- Suspense
- useCallback Hook
- useEffect hook
- useMemo hook
- useReducer hook
- useRef hook
- Virtual DOM
REACT
React Error Boundary: Syntax, Usage, and Examples
A React error boundary is a special component that catches JavaScript errors in part of the component tree and renders a fallback UI instead of crashing the whole app. You use it to improve error handling, isolate failures, and deliver a smoother user experience.
React introduced this concept in version 16 to address a common issue—one broken component shouldn’t break the entire interface. You can implement an error boundary using a class component that defines specific lifecycle methods, or use a library like react-error-boundary
to make integration easier.
How to Use a React Error Boundary
To create a custom React error boundary, write a class component with the following structure:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Caught error:", error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Wrap any risky component or section of your app like this:
<ErrorBoundary>
<UnstableWidget />
</ErrorBoundary>
This structure ensures that if UnstableWidget
throws an error, only that section is replaced with the fallback.
You Can Display Custom Fallback UIs
The fallback UI can be as simple or as detailed as you'd like. It might include an error message, instructions to refresh, or even a retry button.
render() {
if (this.state.hasError) {
return (
<div className="error-message">
<p>Oops, something broke. Try again later.</p>
</div>
);
}
return this.props.children;
}
This approach keeps users informed without exposing raw stack traces.
You Should Use Error Boundaries Around Unstable Features
Use error boundaries around parts of the app most likely to fail. Some common candidates include:
- Lazy-loaded routes
- External libraries
- Complex form logic
- Dynamic widgets
- Charts and data visualizations
Wrapping only unstable parts helps isolate errors without interfering with stable parts of the app.
Syntax of react-error-boundary for Simplified Handling
Instead of writing your own class, you can use the react-error-boundary
package to handle everything more cleanly.
Install it with:
npm install react-error-boundary
And use it like this:
import { ErrorBoundary } from 'react-error-boundary';
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Error: {error.message}</p>
<button onClick={resetErrorBoundary}>Try Again</button>
</div>
);
}
function App() {
return (
<ErrorBoundary FallbackComponent={Fallback}>
<MyComponent />
</ErrorBoundary>
);
}
This allows better control of what happens after an error, like resetting state or triggering analytics.
You Can Catch Errors in Functional Components Using Hooks
React error boundaries themselves must be class components. But with react-error-boundary
, you can use the useErrorHandler
hook to trigger an error from inside a functional component.
import { useErrorHandler } from 'react-error-boundary';
function BuggyComponent() {
const handleError = useErrorHandler();
useEffect(() => {
try {
throw new Error("Something went wrong");
} catch (e) {
handleError(e);
}
}, []);
return <div>This will crash</div>;
}
This allows you to mix modern function-based logic with traditional error boundaries.
Error Boundary React Use Cases
Error boundaries shine in production apps where uptime and graceful degradation matter. Use them to:
- Catch rendering errors
- Prevent full-page crashes
- Inform users of problems
- Log crash reports
In an ecommerce site, for example, if the reviews widget crashes, a React error boundary ensures that the product page still loads.
You Should Avoid These Common Pitfalls
Error boundaries don’t catch every type of error. You won’t be able to intercept:
- Errors in event handlers
- Async code (like
setTimeout
) - Server-side rendering errors
- Errors outside the React tree
You still need try/catch
inside event handlers or network logic. Use tools like window.onerror
or try/catch
blocks in those places.
Best Practices for Using a React Error Boundary
To use error boundaries effectively:
- Be selective: Don’t wrap everything. Use boundaries around risky or user-facing parts.
- Log errors: Use
componentDidCatch
to send errors to tools like Sentry or LogRocket. - Use good fallback design: Show something useful—not just “Oops.”
- Recover if possible: Add retry or refresh buttons.
- Wrap routes or widgets: It’s better to isolate errors than to rely on a global fallback.
These strategies make error boundary React usage feel seamless and user-friendly.
Full React Error Boundary Example
Here’s a complete working version:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
if (this.state.hasError) {
return <p>Sorry, something failed. We're working on it.</p>;
}
return this.props.children;
}
}
And usage:
<ErrorBoundary>
<UserProfile />
</ErrorBoundary>
This structure contains failures without impacting the entire page or app.
You Can Combine Error Boundaries with Suspense
Use error boundaries together with Suspense for lazy-loaded components. Suspense handles loading states, and error boundaries catch loading errors.
<Suspense fallback={<p>Loading...</p>}>
<ErrorBoundary>
<LazyComponent />
</ErrorBoundary>
</Suspense>
This provides full resilience—fallback for loading and fallback for crashing.
Error Boundaries in Server-Side Rendering
React error boundaries don’t apply on the server side because SSR doesn’t use the React lifecycle. You should still handle errors in server-side logic manually. Once the app hydrates on the client, error boundaries start working again.
Summary
The error boundary React pattern helps you manage rendering failures by wrapping risky parts of your UI in specialized components that handle errors gracefully. You can write your own with lifecycle methods or use packages like react-error-boundary
for modern flexibility.
Key takeaways:
- Use class components to define error boundaries.
- Place them strategically around unstable UI parts.
- Customize fallback UIs to match your brand and user needs.
- Use
react-error-boundary
for enhanced control and functional support.
This makes your app more stable, user-friendly, and production-ready.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.