react-error-boundary

repository·main·Indexed 27 days ago

https://github.com/bvaughn/react-error-boundary

A reusable React component for catching errors in the component tree and rendering fallback UIs. It supports all React renderers, including React DOM and React Native. The library provides the ErrorBoundary component, the useErrorBoundary hook for imperative error management, the withErrorBoundary HOC, and the getErrorMessage utility.

Tokens
2.8K
Snippets
7
Records
20
Agent score
93%

What's inside react-error-boundary

  1. Expand ESLint configuration for type-aware linting

    main

    For production applications, it is recommended to enable type-aware lint rules in your ESLint configuration. This involves replacing standard recommended configs with type-checked versions and configuring parserOptions to point to your tsconfig files.

    export default tseslint.config({
      extends: [
        // Remove ...tseslint.configs.recommended and replace with this
        ...tseslint.configs.recommendedTypeChecked,
        // Alternatively, use this for stricter rules
        ...tseslint.configs.strictTypeChecked,
        // Optionally, add this for stylistic rules
        ...tseslint.configs.stylisticTypeChecked,
      ],
      languageOptions: {
        // other options...
        parserOptions: {
          project: ['./tsconfig.node.json', './tsconfig.app.json'],
          tsconfigRootDir: import.meta.dirname,
        },
      },
    })
  2. Add React-specific lint rules to ESLint

    main

    To add React-specific linting, install eslint-plugin-react-x and eslint-plugin-react-dom, then add them to your eslint.config.js plugins and spread their recommended rules into the rules object.

    // eslint.config.js
    import reactX from 'eslint-plugin-react-x'
    import reactDom from 'eslint-plugin-react-dom'
    
    export default tseslint.config({
      plugins: {
        // Add the react-x and react-dom plugins
        'react-x': reactX,
        'react-dom': reactDom,
      },
      rules: {
        // other rules...
        // Enable its recommended typescript rules
        ...reactX.configs['recommended-typescript'].rules,
        ...reactDom.configs.recommended.rules,
      },
    })
  3. Install react-error-boundary

    main

    You can install react-error-boundary using npm, pnpm, or yarn.

    Note: If your project uses a framework or runtime that does not support ES Modules, use version 5 of this library.

    # npm
    npm install react-error-boundary
    
    # pnpm
    pnpm add react-error-boundary
    
    # yarn
    yarn add react-error-boundary
  4. Handle event handler and async errors

    main

    Standard React error boundaries do not catch errors thrown in event handlers or async code (like setTimeout or unresolved promises). To handle these, you have two options:

    1. Use the useErrorBoundary hook to manually pass caught errors to the nearest boundary.
    2. In React 19, use useTransition. Errors thrown from a function passed to the startTransition function are caught by the nearest boundary.
    "use client";
    
    import { useTransition } from "react";
    import { ErrorBoundary } from "react-error-boundary";
    
    function AddCommentContainer() {
      return (
        <ErrorBoundary fallback={<p>Could not add comment</p>}>
          <AddCommentButton />
        </ErrorBoundary>
      );
    }
    
    function AddCommentButton() {
      const [isPending, startTransition] = useTransition();
    
      function handleClick() {
        startTransition(async () => {
          await addComment();
        });
      }
    
      return (
        <button disabled={isPending} onClick={handleClick}>
          {isPending ? "Adding..." : "Add comment"}
        </button>
      );
    }
  5. Fix 'ErrorBoundary cannot be used as a JSX component' error

    main

    This error is often caused by a version mismatch between react and @types/react. Ensure both match exactly.

    If using NPM, use overrides in your package.json. If using Yarn, use resolutions in your package.json.

    // NPM
    {
      "overrides": {
        "@types/react": "17.0.60"
      }
    }
    
    // Yarn
    {
      "resolutions": {
        "@types/react": "17.0.60"
      }
    }
  6. Quick start with ErrorBoundary

    main

    Wrap an ErrorBoundary around the part of the component tree where you want to show a fallback UI if rendering fails. You can use fallbackRender to provide a render prop that receives the error and a resetErrorBoundary function to allow users to retry rendering.

    "use client";
    
    import { ErrorBoundary, getErrorMessage } from "react-error-boundary";
    
    export default function App() {
      return (
        <ErrorBoundary
          fallbackRender={({ error, resetErrorBoundary }) => (
            <div role="alert">
              <p>Something went wrong:</p>
              <pre>{getErrorMessage(error)}</pre>
              <button onClick={resetErrorBoundary}>Try again</button>
            </div>
          )}
          onError={(error, info) => {
            // Log the error to your error reporting service
          }}
          onReset={() => {
            // Reset any state that may have caused the error
          }}
        >
          {/* Components protected by this boundary */}
        </ErrorBoundary>
      );
    }
  7. Provide fallback UI via fallback, FallbackComponent, or fallbackRender

    main

    The ErrorBoundary component supports three mutually exclusive ways to provide fallback UI:

    1. fallback: Pass static ReactNode content to render when an error occurs.
    2. FallbackComponent: Pass a React component that receives FallbackProps (see FallbackProps).
    3. fallbackRender: Pass a render function that receives FallbackProps and returns a ReactNode.
  8. Reference ErrorBoundary Types

    main

    The library exports several types for configuring the ErrorBoundary and its handlers:

    • ErrorBoundaryProps: Base props for the component.
    • ErrorBoundaryPropsWithComponent: Props when using FallbackComponent.
    • ErrorBoundaryPropsWithFallback: Props when using Fallback (a React node).
    • ErrorBoundaryPropsWithRender: Props when using FallbackRender (a function).
    • FallbackProps: Props passed to your fallback component (includes error and resetErrorBoundary).
    • OnErrorCallback: The type for the onReset or onError handler functions.
  9. Use the `useErrorBoundary` hook to imperatively manage error boundaries

    main

    The useErrorBoundary hook provides a way to imperatively show or dismiss the nearest error boundary. This is particularly useful for handling errors that occur in event handlers or asynchronous code, which React does not catch automatically.

    Important Constraints:

    • This hook must be used within an ErrorBoundary component subtree.
    • Use showBoundary(error) to manually trigger the nearest error boundary for errors caught in non-rendering logic (like setTimeout or fetch callbacks).
    • Use resetBoundary() to clear the error and attempt to retry the component tree.