How to Use Error Boundary Concept in JavaScript
In JavaScript, especially with React, an
Error Boundary is a component that catches JavaScript errors anywhere in its child component tree and displays a fallback UI instead of crashing the whole app. You create an error boundary by defining a class component with componentDidCatch and static getDerivedStateFromError methods to handle errors and update the UI.Syntax
An error boundary is a React class component that implements two special lifecycle methods:
static getDerivedStateFromError(error): Updates state to show fallback UI.componentDidCatch(error, info): Logs error details.
The component renders either its children or a fallback UI when an error occurs.
javascript
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state to show fallback UI return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can log error info here console.error('Error caught:', error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
Example
This example shows an error boundary wrapping a component that throws an error. When the error happens, the boundary catches it and shows a fallback message instead of crashing the app.
javascript
import React from 'react'; import ReactDOM from 'react-dom/client'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error('Error caught:', error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } function BuggyComponent() { throw new Error('I crashed!'); // The following line is unreachable and can be removed // return <div>This will not render.</div>; } function App() { return ( <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);
Output
Something went wrong.
Common Pitfalls
- Only class components can be error boundaries; functional components cannot catch errors this way.
- Error boundaries catch errors in their child components, not in themselves.
- They do not catch errors in event handlers, asynchronous code, or server-side rendering.
- Forgetting to update state in
getDerivedStateFromErrormeans fallback UI won't show.
javascript
/* Wrong: Functional component as error boundary (won't catch errors) */ function WrongBoundary({ children }) { try { return children; } catch { return <h1>Error caught</h1>; } } /* Right: Use class component with lifecycle methods as shown in Syntax section */
Quick Reference
Error Boundary Key Points:
- Use a class component with
getDerivedStateFromErrorandcomponentDidCatch. - Wrap components that may throw errors inside the error boundary.
- Show fallback UI by updating state when an error occurs.
- Log errors inside
componentDidCatchfor debugging.
Key Takeaways
Error boundaries are React class components that catch errors in their child components to prevent app crashes.
Implement static getDerivedStateFromError to update UI state and componentDidCatch to log errors.
Error boundaries do not catch errors in event handlers or asynchronous code.
Always wrap potentially error-throwing components inside an error boundary to improve user experience.
Functional components cannot be error boundaries; use class components for this purpose.