Course contentsShow
← React
Lesson 1326 of 2,39633. Error BoundariesFree lesson

The useErrorHandler Hook

Programmatically throwing errors to the nearest boundary from async code or event handlers.

The useErrorHandler Hook

What you'll learn: How to manually throw errors from event handlers or async code into the nearest Error Boundary using react-error-boundary's useErrorHandler hook.

The Problem It Solves

You've learned that Error Boundaries don't catch errors from event handlers or async code (like promise rejections). But what if you want those errors to be handled by your Error Boundary's fallback UI? You need a bridge between non-render errors and the boundary system.

How useErrorHandler Works

The useErrorHandler hook from react-error-boundary gives you a function that programmatically throws an error to the nearest Error Boundary. Think of it as a manual alarm button: when something goes wrong in async code or an event handler, you can pull this alarm to trigger the boundary.

import { useErrorHandler } from 'react-error-boundary';

function DataFetcher() {
  const handleError = useErrorHandler();

  async function fetchData() {
    try {
      const response = await fetch('/api/data');
      if (!response.ok) throw new Error('Fetch failed');
      // ... process data
    } catch (error) {
      handleError(error); // Throws to Error Boundary!
    }
  }

  return <button onClick={fetchData}>Load Data</button>;
}

When handleError(error) is called, React treats it like a render error and triggers the nearest Error Boundary's fallback UI.

Why This Matters

Without this hook, you'd need separate error handling logic for async/event errors versus render errors. useErrorHandler unifies your error handling strategy: one Error Boundary catches everything.

Key Takeaway: useErrorHandler bridges the gap between errors that Error Boundaries naturally catch (render errors) and those they don't (async/event errors), letting you programmatically trigger boundary fallbacks from anywhere in your component.