Bird
Raised Fist0
Reactframework~10 mins

Handling runtime errors in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Handling runtime errors
Component Renders
↓
Error Occurs?
No→Normal UI Display
Yes↓
Error Boundary Catches
↓
Render Fallback UI
↓
User Interaction: Retry or Report
↓
Reset Error State or Log
This flow shows how React components render normally, but if a runtime error happens, an Error Boundary catches it and shows a fallback UI, allowing user recovery.
Execution Sample
React
function BuggyCounter() {
  const [count, setCount] = React.useState(0);
  if (count === 3) throw new Error('Crashed!');
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, errorInfo) {
    console.log(error.message);
  }

  render() {
    if (this.state.error) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
A component that crashes when count reaches 3, wrapped by an error boundary that catches the error and shows fallback UI.
Execution Table
StepActionCount StateError StateRendered OutputNotes
1Initial render BuggyCounter0null<button>0</button>No error, normal render
2Click button, count=11null<button>1</button>No error, normal render
3Click button, count=22null<button>2</button>No error, normal render
4Click button, count=3 triggers error3nullError thrownRuntime error occurs inside component
5ErrorBoundary catches error3Error: Crashed!<h1>Something went wrong.</h1>Fallback UI shown
6User sees fallback UI3Error: Crashed!<h1>Something went wrong.</h1>Error state prevents normal UI
7User reloads or resets error0null<button>0</button>Error cleared, normal UI restored
💡 Execution stops normal rendering when error occurs; ErrorBoundary handles error and shows fallback UI.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
count012330
errornullnullnullnullError: Crashed!null
Key Moments - 3 Insights
Why does the UI stop updating normally after count reaches 3?
Because at count 3, the component throws an error (see step 4 in execution_table), which interrupts normal rendering and triggers the ErrorBoundary fallback.
How does the ErrorBoundary catch errors from its child components?
It uses static getDerivedStateFromError() and componentDidCatch() to catch errors from its child components during rendering, sets an error state when an error is caught (step 5), which then switches the UI to fallback mode.
What happens if the error state is not reset?
The fallback UI remains displayed and the normal UI never returns (step 6), so resetting error state is needed to restore normal rendering (step 7).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the count value when the error is thrown?
A2
B3
C0
Dnull
💡 Hint
Check step 4 in the execution_table where the error occurs.
At which step does the ErrorBoundary show the fallback UI?
AStep 5
BStep 3
CStep 2
DStep 7
💡 Hint
Look for the step where Rendered Output changes to fallback UI in execution_table.
If the error state is never reset, what will the user see?
ANormal button with count 0
BButton with count 3
CFallback UI message
DBlank screen
💡 Hint
Refer to step 6 in execution_table where error state is set but not cleared.
Concept Snapshot
Handling runtime errors in React:
- Use Error Boundaries to catch errors in child components.
- Error Boundary sets error state and renders fallback UI.
- Normal UI stops rendering when error occurs.
- Reset error state to recover UI.
- Helps keep app stable and user informed.
Full Transcript
In React, runtime errors inside components can crash the UI. To handle this, we use Error Boundaries. These are components that catch errors thrown by their children during rendering. When an error happens, the Error Boundary sets an error state and shows a fallback UI instead of the broken component. This prevents the whole app from crashing. Users see a friendly message and can retry or reload to reset the error state. This flow keeps the app stable and improves user experience by handling unexpected errors gracefully.

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