Bird
Raised Fist0
Reactframework~20 mins

Handling runtime errors in React - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
React Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a React component throws an error during rendering?
Consider a React functional component that throws an error inside its body during rendering. What will be the visible result in the browser if no error boundary is used?
React
function BuggyComponent() {
  throw new Error('Oops!');
  return <div>Hello</div>;
}
AThe component renders nothing and the error is silently ignored.
BReact displays the error message on the page automatically.
CReact shows a blank screen and logs the error in the console.
DThe entire React app crashes and unmounts all components.
Attempts:
2 left
💡 Hint
Think about what React does by default when a component throws an error and no error boundary is present.
📝 Syntax
intermediate
2:00remaining
Which code correctly implements an error boundary in React?
Select the option that correctly defines a React error boundary component.
A
function ErrorBoundary({children}) {
  const [hasError, setHasError] = React.useState(false);
  try {
    return children;
  } catch {
    setHasError(true);
    return &lt;div&gt;Error occurred&lt;/div&gt;;
  }
}
B
function ErrorBoundary({children}) {
  try {
    return children;
  } catch {
    return &lt;div&gt;Error occurred&lt;/div&gt;;
  }
}
C
function ErrorBoundary({children}) {
  const [hasError, setHasError] = React.useState(false);
  React.useEffect(() =&gt; {
    window.onerror = () =&gt; setHasError(true);
  }, []);
  if (hasError) return &lt;div&gt;Error occurred&lt;/div&gt;;
  return children;
}
D
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return &lt;div&gt;Error occurred&lt;/div&gt;;
    }
    return this.props.children;
  }
}
Attempts:
2 left
💡 Hint
Error boundaries must be class components with specific lifecycle methods.
🔧 Debug
advanced
2:00remaining
Why does this React error boundary fail to catch errors?
Examine the code below. Why does the error boundary not catch errors thrown inside the component?
React
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) return <div>Error caught</div>;
    return this.props.children;
  }
}

function Child() {
  throw new Error('Crash');
  return <div>Child</div>;
}

function App() {
  return (
    <ErrorBoundary>
      <Child />
    </ErrorBoundary>
  );
}
AErrorBoundary lacks getDerivedStateFromError, so it cannot update state on error.
BcomponentDidCatch does not update state synchronously, so the error is missed.
CErrorBoundary catches errors only in lifecycle methods, not during rendering of children.
DThe error is thrown outside React's render phase, so ErrorBoundary cannot catch it.
Attempts:
2 left
💡 Hint
Check React docs on error boundaries and required methods to update state on error.
❓ state_output
advanced
2:00remaining
What is the state value after an error is caught in this error boundary?
Given the following error boundary, what will be the value of this.state.hasError after Child throws an error?
React
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');
  }
  render() {
    if (this.state.hasError) return <div>Error caught</div>;
    return this.props.children;
  }
}

function Child() {
  throw new Error('Crash');
  return <div>Child</div>;
}

function App() {
  return (
    <ErrorBoundary>
      <Child />
    </ErrorBoundary>
  );
}
Anull
Btrue
Cundefined
Dfalse
Attempts:
2 left
💡 Hint
getDerivedStateFromError updates state when an error happens during rendering.
🧠 Conceptual
expert
2:00remaining
Which statement about React error boundaries is true?
Select the only correct statement about React error boundaries.
AError boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
BError boundaries can be implemented using React hooks in functional components.
CError boundaries catch errors in event handlers and asynchronous code automatically.
DError boundaries prevent errors from propagating to the browser console.
Attempts:
2 left
💡 Hint
Recall what kinds of errors error boundaries catch and how they are implemented.

Practice

(1/5)
1. What is the main purpose of an error boundary in React?
easy
A. To catch runtime errors in child components and display a fallback UI
B. To improve the performance of React components
C. To handle user input validation
D. To manage component state more efficiently

Solution

  1. Step 1: Understand error boundaries role

    Error boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
  2. Step 2: Identify their main use

    They prevent the entire app from crashing by showing a fallback UI instead of the broken component.
  3. Final Answer:

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

    Error boundaries catch errors = D [OK]
Hint: Error boundaries catch errors and show fallback UI [OK]
Common Mistakes:
  • Thinking error boundaries improve performance
  • Confusing error boundaries with input validation
  • Assuming error boundaries manage state
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 functional component with try/catch inside render
D. A class component using componentWillCatch lifecycle method

Solution

  1. Step 1: Recall error boundary requirements

    Error boundaries must be class components that implement static getDerivedStateFromError and componentDidCatch methods.
  2. Step 2: Check options for correct lifecycle methods

    Only A class component implementing componentDidCatch and getDerivedStateFromError correctly names these methods; componentWillCatch does not exist and hooks for error boundaries are not standard.
  3. Final Answer:

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

    Error boundaries require class + lifecycle methods = A [OK]
Hint: Error boundaries are class components with componentDidCatch [OK]
Common Mistakes:
  • Using functional components for error boundaries
  • Using non-existent lifecycle methods
  • Trying to catch errors inside render with try/catch
3. Given this error boundary component, what will be rendered if a child component throws an error during rendering?
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 caught:', error);
  }
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
medium
A. The child component will render normally
B. An error message 'Something went wrong.' will be displayed
C. The app will crash with an uncaught error
D. Nothing will render because of infinite loop

Solution

  1. Step 1: Understand error boundary state update

    When an error occurs, getDerivedStateFromError sets hasError to true, triggering fallback UI.
  2. Step 2: Check render output on error

    If hasError is true, render returns <h1>Something went wrong.</h1> instead of children.
  3. Final Answer:

    An error message 'Something went wrong.' will be displayed -> Option B
  4. Quick Check:

    Error caught triggers fallback UI = C [OK]
Hint: Error sets state to show fallback UI message [OK]
Common Mistakes:
  • Expecting child to render despite error
  • Thinking app crashes without error boundary
  • Assuming infinite loop occurs
4. Identify the error in this error boundary implementation:
class MyErrorBoundary extends React.Component {
  state = { error: null };
  componentDidCatch(error, info) {
    this.setState({ error });
  }
  render() {
    if (this.state.error) {
      return <div>Error occurred</div>;
    }
    return this.props.children;
  }
}
medium
A. State should be initialized in constructor, not as class field
B. Using setState inside componentDidCatch causes infinite loop
C. Missing static getDerivedStateFromError method
D. Error boundary must be a functional component

Solution

  1. Step 1: Check error boundary lifecycle methods

    To update state on error, static getDerivedStateFromError must be implemented to update state before render.
  2. Step 2: Analyze componentDidCatch usage

    componentDidCatch is for side effects like logging, not for state updates; setState here can cause issues.
  3. Final Answer:

    Missing static getDerivedStateFromError method -> Option C
  4. Quick Check:

    State update on error requires getDerivedStateFromError = A [OK]
Hint: Use getDerivedStateFromError to update state on error [OK]
Common Mistakes:
  • Updating state only in componentDidCatch
  • Thinking class fields can't hold state
  • Believing error boundaries can be functional components
5. You want to catch errors in multiple nested components but only show one fallback UI at the top level. Which approach is best?
hard
A. Add error boundaries around each nested component separately
B. Use a functional component with useErrorBoundary hook at each level
C. Use try/catch blocks inside each component's render method
D. Wrap the entire app in a single error boundary component

Solution

  1. Step 1: Understand error boundary scope

    An error boundary catches errors in its child components and their descendants.
  2. Step 2: Choose approach for single fallback UI

    Wrapping the entire app in one error boundary ensures all errors show one fallback UI at top level.
  3. Final Answer:

    Wrap the entire app in a single error boundary component -> Option D
  4. Quick Check:

    One top-level error boundary = B [OK]
Hint: One top-level error boundary catches all nested errors [OK]
Common Mistakes:
  • Adding many error boundaries causing multiple fallback UIs
  • Trying to catch errors with try/catch in render
  • Using non-existent hooks for error boundaries
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