ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Error Boundary for Component Failure Isolation

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1class ErrorBoundary extends React.Component {
2constructor(props) {
3super(props);
4this.state = { hasError: false, error: null, errorInfo: null };
5}
6
7static getDerivedStateFromError(error) {
8// Update state so the next render will show the fallback UI.
9return { hasError: true, error: error };
10}
11
12componentDidCatch(error, errorInfo) {
13// You can also log the error to an error reporting service
14console.error("ErrorBoundary caught an error:", error, errorInfo);
15this.setState({ errorInfo: errorInfo });
16}
17
18render() {
19if (this.state.hasError) {
20// You can render any custom fallback UI
21return (
22<div style={{ border: '1px solid red', padding: '10px', color: 'red' }}>
23<h2>Something went wrong.</h2>
24<p>{this.state.error.message}</p>
25<details style={{ whiteSpace: 'pre-wrap' }}>
26{this.state.errorInfo && (
27<summary>Error Details</summary>
28)}
29{this.state.errorInfo && this.state.errorInfo.componentStack}
30</details>
31<button onClick={() => this.setState({ hasError: false, error: null, errorInfo: null })}>Try Again</button>
32</div>
33);
34}
35
36return this.props.children;
37}
38}
39
40function BrokenComponent() {
41const [count, setCount] = React.useState(0);
42
43if (count > 2) {
44throw new Error('I crashed!');
45}
46
47return (
48<div>
49<p>Count: {count}</p>
50<button onClick={() => setCount(count + 1)}>Increment</button>
51</div>
52);
53}
54
55function App() {
56return (
57<ErrorBoundary>
58<p>This is a normal component.</p>
59<ErrorBoundary>
60<BrokenComponent />
61</ErrorBoundary>
62</ErrorBoundary>
63);
64}
Algorithm description viewbox

Error Boundary for Component Failure Isolation

Algorithm description:

This scenario implements a React Error Boundary component, a crucial pattern for isolating failures in the UI. Error Boundaries catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. This prevents the entire application from crashing due to a single component's error.

Algorithm explanation:

The `ErrorBoundary` component uses `static getDerivedStateFromError` to capture errors thrown by its children and update its state to `hasError: true`. The `componentDidCatch` lifecycle method is then used to log the error and its stack trace to the console or an error reporting service. When `hasError` is true, the `render` method displays a fallback UI. The fallback UI includes the error message and component stack for debugging, and a 'Try Again' button to reset the error state. This pattern ensures that a single component failure does not bring down the entire application. Time complexity is O(1) for error catching and O(1) for rendering the fallback UI. Space complexity is O(1) for storing error information.

Pseudocode:

Define `ErrorBoundary` class component:
  Initialize state: `hasError = false`, `error = null`, `errorInfo = null`.
  Implement `static getDerivedStateFromError(error)`:
    Return `{ hasError: true, error: error }`.
  Implement `componentDidCatch(error, errorInfo)`:
    Log error and `errorInfo`.
    Set state `errorInfo = errorInfo`.
  Implement `render()`:
    If `state.hasError` is true:
      Render fallback UI with error details and a reset button.
    Else:
      Render `this.props.children`.
Implement a `BrokenComponent` that throws an error.
Wrap `BrokenComponent` in `ErrorBoundary` in the `App` component.