Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

What are Error Boundaries in React?

Error Boundaries are special React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire app.

Normally, if an error occurs during rendering, in a lifecycle method, or in a constructor of any child component, it can break the whole UI. Error Boundaries help to gracefully handle such errors without affecting the rest of the application.

Key Points:

  • They catch errors during:
    • Rendering
    • Lifecycle methods
    • Constructors of child components
  • They do not catch errors inside event handlers, asynchronous code (like setTimeout), or server-side rendering.

How to create an Error Boundary: An Error Boundary is simply a React component that implements either (or both) of these lifecycle methods:

  • static getDerivedStateFromError(error)
  • componentDidCatch(error, info)

Here’s a basic example:

import React from "react"; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state to show fallback UI return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can log the error to an error reporting service console.error("Error caught by ErrorBoundary:", error, errorInfo); } render() { if (this.state.hasError) { // Fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } export default ErrorBoundary;

Usage:

<ErrorBoundary> <MyComponent /> </ErrorBoundary>

Important Notes:

  • It's recommended to wrap different parts of your app with different Error Boundaries, rather than a single global one.
  • React 16 and later versions introduced Error Boundaries.
  • They improve user experience by preventing complete app crashes.