Skip to Content
Nextjs1.6 Error Boundaries

Error Boundaries 🛡️

Error boundaries are crash pads for your component tree—they catch render errors below them and show fallback UI instead of white screens.

Conceptual Model 🧠

  • They catch errors during render, lifecycle methods, and constructors of child components.
  • They don’t catch event handler errors (handle those inside the handler) or server-side exceptions.

Basic Implementation 🧱

'use client'; import { Component, ReactNode } from 'react'; class ErrorBoundary extends Component<{ fallback: ReactNode }, { hasError: boolean }> { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error: Error, info: React.ErrorInfo) { console.error('Boundary caught', error, info); } render() { if (this.state.hasError) return this.props.fallback; return this.props.children; } }

Use it by wrapping risky UI:

<ErrorBoundary fallback={<p>Something broke 😢</p>}> <Chart /> </ErrorBoundary>

Next.js App Router Specifics 🧭

  • Use error.tsx files in route segments for automatic boundaries (server and client aware).
  • Client-only boundaries still useful around widgets (charts, embeds) that may fail after hydration.
  • Combine with useEffect to reset boundary when props change (this.setState({ hasError: false })).

Patterns 🧩

  • Retry buttons: store error info in state, offer a “Try again” action.
  • Per-widget boundaries: isolate third-party components so they can’t crash the entire page.
  • Logging: send errors to Sentry, LogRocket, etc., inside componentDidCatch.

Analogy: error boundaries are circuit breakers—you install them per floor so one faulty appliance doesn’t darken the whole building.

Plan boundary placement early to keep Next.js experiences resilient. 💪

Last updated on