FrontendPro

73Implement an error boundary with retry/reset behavior

mediumAbout 35 minutesCodingreacterror-handlingclass-components

Problem

Implement <ErrorBoundary fallback={…} onError={…} resetKeys={[…]}>. When a component inside it throws while rendering, show a fallback instead of a blank page, and let the user recover.

  • fallback is a function ({ error, reset }) => ReactNode.
  • onError(error, info) is called once per caught error (for logging).
  • reset() clears the error and renders the children again.
  • When any value in resetKeys changes (compared with Object.is), the boundary resets automatically. For example, navigating to another item should clear the previous item's error.
<ErrorBoundary
  resetKeys={[productId]}
  onError={(error) => logToSentry(error)}
  fallback={({ error, reset }) => (
    <div role="alert">
      <p>Something went wrong: {error.message}</p>
      <button onClick={reset}>Try again</button>
    </div>
  )}
>
  <ProductDetails id={productId} />
</ErrorBoundary>

Requirements

  • Error boundaries must be class components: use static getDerivedStateFromError and componentDidCatch.
  • If the children still throw after a reset, show the fallback again.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

state = { error: null }. While it is null, render the children; otherwise render the fallback.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever