Docs
useErrorBoundary

Handle errors in React components gracefully with the useErrorBoundary hook, providing a way to catch and display errors without crashing the application.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-error-boundary

Usage

"use client"
 
import * as React from "react"
 
import { useErrorBoundary } from "@/hooks/use-error-boundary"
 
function FaultyComponent() {
  const [count, setCount] = React.useState(0)
 
  if (count >= 3) {
    throw new Error("Count exceeded limit of 3")
  }
 
  return (
    <button
      onClick={() => setCount(count + 1)}
      className="rounded bg-blue-500 px-4 py-2 text-white"
    >
      Increment Count: {count}
    </button>
  )
}
 
function ErrorFallback({ reset }: { reset: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center gap-3">
      <h2>Something went wrong!</h2>
      <button
        onClick={reset}
        className="rounded bg-blue-500 px-4 py-2 text-white"
      >
        Try Again
      </button>
    </div>
  )
}
 
export function Component() {
  const { ErrorBoundary, hasError, error, resetError } = useErrorBoundary()
 
  return (
    <div>
      <ErrorBoundary fallback={<ErrorFallback reset={resetError} />}>
        <FaultyComponent />
      </ErrorBoundary>
      {hasError && error && (
        <div>
          <p>Error: {error.message}</p>
        </div>
      )}
    </div>
  )
}

API Reference

Return Values

NameTypeDescription
hasErrorbooleanIndicates if an error has occurred in the boundary.
errorError | nullThe error object if an error has occurred.
resetError() => voidFunction to reset the error state in the boundary.
ErrorBoundaryReact.ComponentTypeThe ErrorBoundary component that can be used to wrap components.
ErrorBoundaryProps{ children: React.ReactNode, fallback?: React.ReactNode }Props for the ErrorBoundary component, including children and an optional fallback UI.