github bvaughn/react-error-boundary 4.0.0

latest releases: 4.0.13, 4.0.12, 4.0.11...
18 months ago
  • Replace useErrorHandler hook with useErrorBoundary; can be used to trigger an error boundary or dismiss one
  • Merge onReset and onResetKeys props; pass "details" object explaining the cause of the reset

Why did the useErrorHandler hook change?

The old hook had two design flaws, both related to the givenError parameter:

  1. All the hook did was throw this value. This seemed unnecessary, because if a component already has a reference to an error during render, it can just throw the value itself.
  • It would not properly re-throw null or undefined values. (Although an edge case, JavaScript enables throwing any values/types.)

If you were using the givenError functionality– you can now just throw the value directly instead.

// Before
function Greeting() {
  const [name, setName] = React.useState('')
  const {greeting, error} = useGreeting(name)
  useErrorHandler(error)
// After
function Greeting() {
  const [name, setName] = React.useState('')
  const {greeting, error} = useGreeting(name)
  if (error) {
    throw error;
  }

How can I use the new useErrorHandler hook?

Show the nearest error boundary from an event handler

React only handles errors thrown during render or during component lifecycle methods (e.g. effects and did-mount/did-update). Errors thrown in event handlers, or after async code has run, will not be caught.

This hook can be used to pass those errors to the nearest error boundary:

import { useErrorBoundary } from "react-error-boundary";

function Example() {
  const { showBoundary } = useErrorBoundary();

  useEffect(() => {
    fetchGreeting(name).then(
      response => {
        // Set data in state and re-render
      },
      error => {
        // Show error boundary
        showBoundary(error);
      }
    );
  });

  // Render ...
}

Dismiss the nearest error boundary

A fallback component can use this hook to request the nearest error boundary retry the render that original failed.

import { useErrorBoundary } from "react-error-boundary";

function ErrorFallback({ error }) {
  const { resetBoundary } = useErrorBoundary();

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
      <button onClick={resetBoundary}>Try again</button>
    </div>
  );
}

Don't miss a new react-error-boundary release

NewReleases is sending notifications on new releases.