React / Next.js

Error Boundaries & Error Handling

Error boundaries, componentDidCatch, error fallback, error recovery, logging strategies

18 interview questionsยท
Senior
1

What is an Error Boundary in React?

Answer

An Error Boundary is a React class component that catches JavaScript errors occurring in its child component tree, displays a fallback UI, and prevents the entire application from crashing. It uses componentDidCatch() and getDerivedStateFromError() methods to intercept and handle rendering errors.

2

Why use Error Boundaries instead of classic try/catch in React?

Answer

Try/catch blocks cannot catch errors occurring during React component rendering, as these errors propagate up the tree asynchronously. Error Boundaries are specifically designed to intercept rendering errors, lifecycle errors, and constructor errors in child components, while try/catch only works for synchronous imperative code.

3

Which lifecycle method allows capturing an error in an Error Boundary?

Answer

componentDidCatch(error, info) is the lifecycle method invoked after an error has been caught by the Error Boundary. It receives the error and an info object containing componentStack, allowing error logging or side-effect actions. Note that getDerivedStateFromError() is also used but to update state and display fallback UI.

4

What is the role of getDerivedStateFromError() in an Error Boundary?

5

What is the difference between getDerivedStateFromError() and componentDidCatch()?

+15 interview questions

Master React / Next.js for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free