React Interview Questions (Part 10): Handling Errors

Yusuf UysalYusuf Uysal
2 min read

1. What are error boundaries in React, and how do you implement them?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. They catch errors during rendering, lifecycle methods, and constructors but do not catch errors in event handlers or async code.

First, create the ErrorBoundary component:

class ErrorBoundary extends React.Component {
  state = { hasError: false };

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

  componentDidCatch(error, info) {
    console.error("Error logged:", error, info);
  }

  render() {
    return this.state.hasError ? <h1>Something went wrong.</h1> : this.props.children;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
  );
}

2. What errors can be caught by error boundaries, and what errors are not caught?

Caught by error boundaries:

  • Errors during rendering.

  • Errors in lifecycle methods like componentDidMount.

  • Errors in constructors of components.

Not caught by error boundaries:

  • Errors in event handlers (use try/catch).

  • Errors in async code (setTimeout, fetch).

  • Errors in server-side rendering (SSR).

3. What are some best practices for handling errors in React applications?

  • Use Error Boundaries: Catch rendering errors with error boundaries.

  • Log Errors: Use services like Sentry for error logging and monitoring.

  • Fallback UI: Always show a fallback UI when an error occurs.

  • Handle Async Errors: Use try/catch blocks for async operations.

  • Test for Edge Cases: Ensure that edge cases, like failed API requests, are tested.

4. How can you handle errors outside the scope of error boundaries, like event handlers or async code?

For event handlers:

function handleClick() {
  try {
    // Error-prone code
  } catch (error) {
    console.error("Error caught:", error);
  }
}

For async code:

async function fetchData() {
  try {
    const data = await fetch("/api");
  } catch (error) {
    console.error("Error in async function:", error);
  }
}

5. How can you ensure reliable error handling when working with third-party APIs in React applications?

  • Validate API Responses: Always check API responses for errors (e.g., status codes).

  • Fallback UI: Show user-friendly fallback content when API calls fail.

  • Retry Mechanism: Implement retries for temporary API failures.

  • Error Logging: Log API failures to an external service.

async function fetchData() {
  try {
    const response = await fetch("/api/data");
    if (!response.ok) throw new Error("API request failed");
    const data = await response.json();
  } catch (error) {
    console.error("API error:", error);
  }
}
0
Subscribe to my newsletter

Read articles from Yusuf Uysal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yusuf Uysal
Yusuf Uysal

๐——๐—ฟ๐—ถ๐˜ƒ๐—ฒ๐—ป ๐—™๐—ฟ๐—ผ๐—ป๐˜๐—ฒ๐—ป๐—ฑ ๐——๐—ฒ๐˜ƒ๐—ฒ๐—น๐—ผ๐—ฝ๐—ฒ๐—ฟ with extensive experience in JavaScript, React.js, and Next.js. I help companies enhance user engagement and deliver high-performance web applications that are responsive, accessible, and visually appealing. Beyond my technical skills, I am a ๐—ฐ๐—ผ๐—น๐—น๐—ฎ๐—ฏ๐—ผ๐—ฟ๐—ฎ๐˜๐—ถ๐˜ƒ๐—ฒ ๐˜๐—ฒ๐—ฎ๐—บ ๐—ฝ๐—น๐—ฎ๐˜†๐—ฒ๐—ฟ who thrives in environments that value continuous learning and innovation. I enjoy projects where I can leverage my expertise in ๐—ฟ๐—ฒ๐˜€๐—ฝ๐—ผ๐—ป๐˜€๐—ถ๐˜ƒ๐—ฒ ๐—ฑ๐—ฒ๐˜€๐—ถ๐—ด๐—ป, ๐—ฏ๐—ฟ๐—ผ๐˜„๐˜€๐—ฒ๐—ฟ ๐—ฐ๐—ผ๐—บ๐—ฝ๐—ฎ๐˜๐—ถ๐—ฏ๐—ถ๐—น๐—ถ๐˜๐˜†, ๐—ฎ๐—ป๐—ฑ ๐˜„๐—ฒ๐—ฏ ๐—ฝ๐—ฒ๐—ฟ๐—ณ๐—ผ๐—ฟ๐—บ๐—ฎ๐—ป๐—ฐ๐—ฒ to deliver seamless user experiences. I get excited about opportunities where I can contribute to creating dynamic, user-focused applications while working closely with cross-functional teams to drive impactful results. I love connecting with new people, and you can reach me at yusufuysal.dev@gmail.com.