22. What are error boundaries in React and how do you use them?

Error boundaries in React are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. Error boundaries cannot catch errors inside themselves, in asynchronous code, or in event handlers.

How to create error boundaries:

  1. Create a class component that implements the componentDidCatch and getDerivedStateFromError methods:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
  1. Wrap the components that may generate errors with the error boundary:
<ErrorBoundary> <MyComponent /> </ErrorBoundary>

Error boundaries are essential for ensuring that errors in child components do not crash the entire application.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.