Skip to content
Advanced PatternsChapter 28 / 37Intermediate4 min read

Error Boundaries

React error boundary se render errors pakar kar poori app crash hone se bachana seekhein, class component, react-error-boundary aur reset ke saath.

On this page

1. Error Boundary kya hai?

React mein agar kisi component ke render mein error aaye aur koi usay na pakre, to React poora root unmount kar deta hai. User ko khali safed screen dikhti hai.

Error Boundary JavaScript ke try/catch jaisa hai, lekin components ke tree ke liye.

2. Kyun zaroori hai?

Bina Error BoundaryError Boundary ke saath
Ek widget ka error, poori app safedSirf woh widget fallback dikhata hai
User ko pata nahi kya huaSaaf message aur Try again button
Error kahin log nahi hotacomponentDidCatch mein error reporting
Reload ke ilawa koi rasta nahiReset kar ke dobara render

3. Kahan use hota hai?

JagahKyun
Poori app ke uparLast line of defense, generic error page
Har route ya page ke girdEk page ka error baqi navigation ko na tode
Third-party widget, chart, mapBahar ka code crash kare to sirf woh hissa
use(promise) wale componentsRejected Promise ka error yahan aata hai

Next.js App Router mein error.tsx file khud ek Error Boundary banati hai.

4. Kaise kaam karta hai?

Error se fallback tak
Child component render mein error throw karta hai
React tree mein upar sab se qareebi Error Boundary dhoondta hai
getDerivedStateFromError state update karta hai
Boundary children ki jagah fallback render karta hai
componentDidCatch error ko log karta hai

5. Code example

Class component boundary

Error Boundary abhi bhi class component se hi banti hai, kyunke iske liye koi hook nahi hai.

tsx
import { Component, type ErrorInfo, type ReactNode } from "react";

type Props = { fallback: ReactNode; children: ReactNode };
type State = { hasError: boolean };

export class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false };

  static getDerivedStateFromError(): State {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback;
    }
    return this.props.children;
  }
}
tsx
<ErrorBoundary fallback={<p>Chart load nahi ho saka.</p>}>
  <SalesChart />
</ErrorBoundary>

react-error-boundary library ke saath reset

tsx
import { ErrorBoundary, type FallbackProps } from "react-error-boundary";

function Fallback({ error, resetErrorBoundary }: FallbackProps) {
  return (
    <div role="alert">
      <p>Kuch ghalat ho gaya: {error instanceof Error ? error.message : "Unknown error"}</p>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

export function Dashboard() {
  return (
    <ErrorBoundary FallbackComponent={Fallback}>
      <SalesChart />
    </ErrorBoundary>
  );
}

Code kaise kaam kar raha hai?

CheezMatlab
getDerivedStateFromErrorError aate hi state hasError: true
componentDidCatchLogging ya Sentry jaisi service ko report
info.componentStackKis component tree mein error aaya
fallbackError ke waqt dikhne wala UI
resetErrorBoundaryState reset, children dobara render ki koshish

React 19 mein createRoot ke onCaughtError aur onUncaughtError options bhi hain, jahan aap saare errors ek jagah report kar sakte hain.

6. Common mistakes

Galati: onClick ke error ke liye Error Boundary par bharosa

Why? Event handler render ke dauran nahi chalta, is liye boundary us error ko kabhi nahi dekhti.

Behtar: Handler ke andar try catch likhein aur error ko state mein rakh kar UI dikhayein.

Galati: Poori app ke liye sirf ek boundary

Why? Ek chhote widget ka error bhi poora page fallback mein badal deta hai.

Behtar: Top par ek boundary rakhein, aur ahem sections ya widgets ke gird alag boundaries.

Galati: Fallback mein reset ka koi rasta na dena

Why? User page reload karne par majboor hota hai aur form data kho deta hai.

Behtar: Try again button dein jo boundary reset kare, jaise react-error-boundary ka resetErrorBoundary.

Interview tip

Poocha ja sakta hai "Function component Error Boundary ban sakta hai?" Jawab: khud nahi, abhi tak sirf class component getDerivedStateFromError aur componentDidCatch de sakta hai. Function components ke liye react-error-boundary library wrapper deti hai.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
Kya haiRender errors pakar kar fallback dikhane wala component
Banta kaise haiClass component, getDerivedStateFromError
LoggingcomponentDidCatch(error, info)
Nahi pakartaEvent handlers, async code, SSR, khud apna error
Easy optionreact-error-boundary library
Next.jserror.tsx file