Error boundaries help catch errors in parts of your app so the whole app doesn't crash. They show a fallback UI instead of a broken screen.
Error boundaries concept in React
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can log the error here } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
Error boundaries must be class components in React.
They catch errors in their child components during rendering, lifecycle methods, and constructors.
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } render() { if (this.state.hasError) { return <div>Oops! Error caught.</div>; } return this.props.children; } }
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 <h2>Failed to load this part.</h2>; } return this.props.children; } }
This app uses an error boundary to catch an error thrown by BuggyComponent. Instead of crashing, it shows a friendly message.
import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log('Error caught:', error.message); } render() { if (this.state.hasError) { return <h1>Oops! Something went wrong.</h1>; } return this.props.children; } } function BuggyComponent() { throw new Error('Bug happened!'); // return <div>This will not render.</div>; } export default function App() { return ( <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> ); }
Error boundaries do not catch errors inside event handlers.
Use multiple error boundaries to isolate errors in different parts of your app.
Always provide a fallback UI to keep your app user-friendly.
Error boundaries catch errors in child components to prevent app crashes.
They must be class components with special lifecycle methods.
Use them to show fallback UI and log errors for better user experience.
Practice
Error Boundary in React?Solution
Step 1: Understand Error Boundary role
Error boundaries catch errors in the components below them in the tree to prevent the whole app from crashing.Step 2: Identify the correct purpose
They show a fallback UI when an error happens, improving user experience.Final Answer:
To catch JavaScript errors in child components and display a fallback UI -> Option AQuick Check:
Error boundaries catch errors = C [OK]
- Confusing error boundaries with state management
- Thinking error boundaries optimize rendering
- Assuming error boundaries handle input validation
Solution
Step 1: Recall Error Boundary requirements
Error boundaries must be class components that implementcomponentDidCatchandgetDerivedStateFromErrorlifecycle methods.Step 2: Identify correct lifecycle methods
Only A class component implementingcomponentDidCatchandgetDerivedStateFromErrorlists these two required methods correctly.Final Answer:
A class component implementing componentDidCatch and getDerivedStateFromError -> Option AQuick Check:
Class + componentDidCatch + getDerivedStateFromError = A [OK]
- Thinking functional components can be error boundaries
- Confusing lifecycle methods needed for error boundaries
- Using hooks that don't exist for error boundaries
ChildComponent throws an error?
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log('Error logged:', error);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Usage:
// <ErrorBoundary><ChildComponent /></ErrorBoundary>Solution
Step 1: Understand error handling in ErrorBoundary
IfChildComponentthrows an error,getDerivedStateFromErrorsetshasErrorto true.Step 2: Check render output when error occurs
WhenhasErroris true, the component renders the fallback UI: <h1>Something went wrong.</h1>.Final Answer:
An error message Something went wrong. is shown -> Option DQuick Check:
Error caught shows fallback UI = D [OK]
- Expecting child UI to show despite error
- Thinking error causes app crash
- Assuming blank screen on error
class MyErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
componentDidCatch(error, info) {
this.setState({ error });
}
render() {
if (this.state.error) {
return <h2>Error occurred</h2>;
}
return this.props.children;
}
}Solution
Step 1: Check error state update method
Error boundaries must implementgetDerivedStateFromErrorto update state when an error happens.Step 2: Identify missing static method
This code only usescomponentDidCatchto set state, which is incorrect becausecomponentDidCatchis for side effects, not state updates.Final Answer:
It lacks the static method getDerivedStateFromError to update state on error -> Option BQuick Check:
Missing getDerivedStateFromError static method = A [OK]
- Updating state inside componentDidCatch
- Forgetting static getDerivedStateFromError
- Misusing lifecycle methods for error handling
class LoggingErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
// ???
}
render() {
if (this.state.hasError) {
return <div><h1>Oops!</h1><p>Try refreshing.</p></div>;
}
return this.props.children;
}
}
What should replace // ??? to correctly log errors without causing issues?Solution
Step 1: Understand componentDidCatch role
componentDidCatch is for side effects like logging errors but should handle errors safely to avoid crashing.Step 2: Choose safe logging approach
Using try/catch inside componentDidCatch when calling async logging prevents unhandled errors from breaking the app.Final Answer:
Use a try/catch inside componentDidCatch to call the logging service safely -> Option CQuick Check:
Safe error logging with try/catch in componentDidCatch = B [OK]
- Calling async logging without error handling
- Updating state inside componentDidCatch causing loops
- Skipping logging and losing error info
Ready to prove it?
Pass the test and this pattern moves unknown
