npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-error-boundary

v3.0.0

Published

A React error boundary hook for function components

Downloads

37,981

Readme

react-use-error-boundary

What is this? 🧐

React 16 introduced Error Boundaries. As of React 18, there still is no equivalent hook for function components.

This library draws inspiration from Preact's useErrorBoundary and attempts to recreate a similar API.

Installation & Usage 📦

  1. Add this package to your project:
    • yarn add react-use-error-boundary

Just trying things out or want to skip the build step? Use the unpkg URL:

<script src="https://unpkg.com/react-use-error-boundary/index.production.js"></script>

Examples 🚀

Whenever the component or a child component throws an error you can use this hook to catch the error and display an error UI to the user.

// error = The error that was caught or `undefined` if nothing
//   errored. If something other than an instance of `Error`
//   was thrown, it will be wrapped in an `Error` object by calling
//   `new Error()` on the thrown value.
//
// resetError = Call this function to mark an error as resolved. It's
//   up to your app to decide what that means and if it is possible
//   to recover from errors.
//
const [error, resetError] = useErrorBoundary();

For application monitoring, it's often useful to notify a service of any errors. useErrorBoundary accepts an optional callback that will be invoked when an error is encountered. The callback is invoked with error and errorInfor which are identical to React's componentDidCatch arguments. Identical to React, error is the error that was thrown, and errorInfo is the component stack trace.

const [error] = useErrorBoundary((error, errorInfo) =>
  logErrorToMyService(error, errorInfo)
);

A full example may look like this:

import { withErrorBoundary, useErrorBoundary } from "react-use-error-boundary";

const App = withErrorBoundary(({ children }) => {
  const [error, resetError] = useErrorBoundary(
    // You can optionally log the error to an error reporting service
    (error, errorInfo) => logErrorToMyService(error, errorInfo)
  );

  if (error) {
    return (
      <div>
        <p>{error.message}</p>
        <button onClick={resetError}>Try again</button>
      </div>
    );
  }

  return <div>{children}</div>;
});

Note that in addition to the hook, the component must be wrapped with withErrorBoundary. This function wraps the component with an Error Boundary and a context provider.

This was done to avoid hooking into React internals, which would otherwise be required. The hope is that the eventual React hook solution will present a similar API, and users can easily migrate by removing the withErrorBoundary wrapper.

Alternatively, the <ErrorBoundaryContext> component from this library may be placed in your component tree, above each component using useErrorBoundary, instead of wrapping the component with withErrorBoundary:

import {
  ErrorBoundaryContext,
  useErrorBoundary,
} from "react-use-error-boundary";

const App = ({ children }) => {
  // ... see function body in example above
};

export default (
  <ErrorBoundaryContext>
    <App />
  </ErrorBoundaryContext>
);

For a full project example take a look at the example.

Known Limitations ⚠️

Because React recreates the component tree from scratch after catching an error, the component using the useErrorBoundary hook is always remounted after an error is encountered. This means any state will be reinitialized: useState and useRef hooks will be reinitialized to their initial value and will not persist across caught errors. Any values that need to be preserved across error catching must be lifted into a parent component above the component wrapped in withErrorBoundary.

Highlights

🌲 Tree shakeable. Ships ES Modules.

🎁 Zero run time dependencies

🦶 Small footprint 673 B minified and gzipped

🪐 Isomorphic / Universal -- safe to run in any JS context: the browser or on a server

🛠 This library follows semantic versioning

Contributing 👫

PR's and issues welcomed! For more guidance check out CONTRIBUTING.md

Licensing 📃

See the project's MIT License.