Bird
Raised Fist0
Reactframework~20 mins

Error boundaries concept in React - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Error Boundary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an error occurs inside a child component wrapped by an error boundary?
Consider a React app where a parent component uses an error boundary to wrap a child component. If the child component throws an error during rendering, what will be the visible result?
React
function ErrorBoundary({children}) {
  const [hasError, setHasError] = React.useState(false);
  React.useEffect(() => {
    // This is a simplified example, real error boundaries use componentDidCatch
  }, []);
  if (hasError) {
    return <div>Something went wrong.</div>;
  }
  return children;
}

function BuggyComponent() {
  throw new Error('Crash!');
  return <div>All good</div>;
}

function App() {
  return <ErrorBoundary><BuggyComponent /></ErrorBoundary>;
}
AThe error is ignored and the buggy component renders normally.
BThe error boundary catches the error and displays 'Something went wrong.' instead of the buggy component.
CThe app crashes completely and shows a blank screen.
DThe error boundary logs the error but still renders the buggy component's output.
Attempts:
2 left
💡 Hint
Think about what error boundaries are designed to do in React.
❓ lifecycle
intermediate
1:30remaining
Which lifecycle method is used in class components to catch errors for error boundaries?
In React class components, which lifecycle method allows an error boundary to catch errors from its child components?
AcomponentDidCatch(error, info)
BshouldComponentUpdate(nextProps, nextState)
CcomponentWillUnmount()
DgetDerivedStateFromError(error)
Attempts:
2 left
💡 Hint
This method receives error details and is called after an error is thrown.
📝 Syntax
advanced
2:30remaining
Identify the correct way to define an error boundary using a class component.
Which of the following class components correctly implements an error boundary in React?
A
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.log(error, info);
  }
  render() {
    if (this.state.hasError) {
      return &lt;h1&gt;Oops!&lt;/h1&gt;;
    }
    return this.props.children;
  }
}
B
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return &lt;h1&gt;Error!&lt;/h1&gt;;
    }
    return this.props.children;
  }
}
C
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  getDerivedStateFromError(error) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return &lt;h1&gt;Error caught&lt;/h1&gt;;
    }
    return this.props.children;
  }
}
D
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  componentDidCatch(error, info) {
    this.state.hasError = true;
  }
  render() {
    if (this.state.hasError) {
      return &lt;h1&gt;Error!&lt;/h1&gt;;
    }
    return this.props.children;
  }
}
Attempts:
2 left
💡 Hint
Remember that getDerivedStateFromError is static and returns new state, and state should not be mutated directly.
🔧 Debug
advanced
2:00remaining
Why does this functional component error boundary not catch errors?
Look at this React functional component intended as an error boundary. Why does it fail to catch errors from its children? function ErrorBoundary({children}) { try { return children; } catch (e) { return
Error caught
; } } function Buggy() { throw new Error('Oops'); return
Safe
; } function App() { return ; }
AThe error boundary must use useEffect hook to catch errors in children.
BThe try/catch block is missing a finally clause to handle errors properly.
CReact error boundaries must be class components; try/catch in functional components does not catch render errors.
DThe Buggy component does not throw an error during rendering, so no error is caught.
Attempts:
2 left
💡 Hint
Think about how React handles errors during rendering and the limitations of try/catch in JSX.
🧠 Conceptual
expert
2:30remaining
What is the main limitation of React error boundaries regarding error types they can catch?
Error boundaries in React catch errors in their child components. Which of the following best describes a limitation of error boundaries?
AThey catch all JavaScript errors anywhere in the app, including event handlers and asynchronous code.
BThey catch errors only in functional components but not in class components.
CThey only catch errors in server-side rendering but not in client-side rendering.
DThey catch errors during rendering, lifecycle methods, and constructors of child components but not errors in event handlers.
Attempts:
2 left
💡 Hint
Consider where React error boundaries are designed to catch errors and where they do not.

Practice

(1/5)
1. What is the main purpose of an Error Boundary in React?
easy
A. To catch JavaScript errors in child components and display a fallback UI
B. To manage state across multiple components
C. To optimize rendering performance
D. To handle user input validation

Solution

  1. 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.
  2. Step 2: Identify the correct purpose

    They show a fallback UI when an error happens, improving user experience.
  3. Final Answer:

    To catch JavaScript errors in child components and display a fallback UI -> Option A
  4. Quick Check:

    Error boundaries catch errors = C [OK]
Hint: Error boundaries catch errors and show fallback UI [OK]
Common Mistakes:
  • Confusing error boundaries with state management
  • Thinking error boundaries optimize rendering
  • Assuming error boundaries handle input validation
2. Which of the following is the correct way to define an Error Boundary component in React?
easy
A. A class component implementing componentDidCatch and getDerivedStateFromError
B. A functional component using useErrorBoundary hook
C. A class component implementing componentDidMount and shouldComponentUpdate
D. A functional component with useEffect to catch errors

Solution

  1. Step 1: Recall Error Boundary requirements

    Error boundaries must be class components that implement componentDidCatch and getDerivedStateFromError lifecycle methods.
  2. Step 2: Identify correct lifecycle methods

    Only A class component implementing componentDidCatch and getDerivedStateFromError lists these two required methods correctly.
  3. Final Answer:

    A class component implementing componentDidCatch and getDerivedStateFromError -> Option A
  4. Quick Check:

    Class + componentDidCatch + getDerivedStateFromError = A [OK]
Hint: Error boundaries are class components with special lifecycle methods [OK]
Common Mistakes:
  • Thinking functional components can be error boundaries
  • Confusing lifecycle methods needed for error boundaries
  • Using hooks that don't exist for error boundaries
3. Given this Error Boundary class component, what will be rendered if 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>
medium
A. The original ChildComponent UI is shown
B. The app crashes with an uncaught error
C. Nothing is rendered (blank screen)
D. An error message Something went wrong. is shown

Solution

  1. Step 1: Understand error handling in ErrorBoundary

    If ChildComponent throws an error, getDerivedStateFromError sets hasError to true.
  2. Step 2: Check render output when error occurs

    When hasError is true, the component renders the fallback UI: <h1>Something went wrong.</h1>.
  3. Final Answer:

    An error message Something went wrong. is shown -> Option D
  4. Quick Check:

    Error caught shows fallback UI = D [OK]
Hint: Error sets state to show fallback UI, not original child [OK]
Common Mistakes:
  • Expecting child UI to show despite error
  • Thinking error causes app crash
  • Assuming blank screen on error
4. What is wrong with this Error Boundary component code?
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;
  }
}
medium
A. componentDidCatch should not call setState
B. It lacks the static method getDerivedStateFromError to update state on error
C. The constructor should not initialize state
D. render method must not return children

Solution

  1. Step 1: Check error state update method

    Error boundaries must implement getDerivedStateFromError to update state when an error happens.
  2. Step 2: Identify missing static method

    This code only uses componentDidCatch to set state, which is incorrect because componentDidCatch is for side effects, not state updates.
  3. Final Answer:

    It lacks the static method getDerivedStateFromError to update state on error -> Option B
  4. Quick Check:

    Missing getDerivedStateFromError static method = A [OK]
Hint: State update on error must be in getDerivedStateFromError [OK]
Common Mistakes:
  • Updating state inside componentDidCatch
  • Forgetting static getDerivedStateFromError
  • Misusing lifecycle methods for error handling
5. You want to create an Error Boundary that logs errors to an external service and shows a fallback UI. Which of the following is the best approach?
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?
hard
A. Call an async logging function directly without try/catch
B. Update state again inside componentDidCatch to trigger re-render
C. Use a try/catch inside componentDidCatch to call the logging service safely
D. Ignore logging and only show fallback UI

Solution

  1. Step 1: Understand componentDidCatch role

    componentDidCatch is for side effects like logging errors but should handle errors safely to avoid crashing.
  2. Step 2: Choose safe logging approach

    Using try/catch inside componentDidCatch when calling async logging prevents unhandled errors from breaking the app.
  3. Final Answer:

    Use a try/catch inside componentDidCatch to call the logging service safely -> Option C
  4. Quick Check:

    Safe error logging with try/catch in componentDidCatch = B [OK]
Hint: Wrap logging calls in try/catch inside componentDidCatch [OK]
Common Mistakes:
  • Calling async logging without error handling
  • Updating state inside componentDidCatch causing loops
  • Skipping logging and losing error info
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard