What if one tiny bug could crash your whole app--unless you catch it early?
Why Error boundaries concept in React? - Purpose & Use Cases
Imagine building a React app where a small mistake in one component crashes the entire page, leaving users staring at a blank screen with no clue what went wrong.
Without error boundaries, a single error bubbles up and breaks the whole app. This makes debugging hard and ruins user experience because the app stops working completely.
Error boundaries catch errors in parts of the UI and show a fallback UI instead of crashing everything. This keeps the app running smoothly and helps developers find and fix bugs faster.
function App() {
return <BuggyComponent />;
}
// If BuggyComponent throws, whole app crashesclass ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { this.setState({ hasError: true }); } render() { return this.state.hasError ? <FallbackUI /> : this.props.children; } } function App() { return <ErrorBoundary><BuggyComponent /></ErrorBoundary>; }
It enables building resilient React apps that stay alive and user-friendly even when parts of the UI fail unexpectedly.
Think of a social media feed where one broken post doesn't crash the entire feed, letting users keep scrolling and interacting with other posts.
Manual error handling can crash the whole React app.
Error boundaries catch errors and show fallback UI.
This improves user experience and helps debugging.
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
