React Interview Questions (Part 10): Handling Errors
Table of contents
- 1. What are error boundaries in React, and how do you implement them?
- 2. What errors can be caught by error boundaries, and what errors are not caught?
- 3. What are some best practices for handling errors in React applications?
- 4. How can you handle errors outside the scope of error boundaries, like event handlers or async code?
- 5. How can you ensure reliable error handling when working with third-party APIs in React applications?
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);
}
}
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.