function BuggyComponent() { throw new Error('Oops!'); return <div>Hello</div>; }
When a React component throws an error during rendering and there is no error boundary, React stops rendering that component tree and shows a blank screen. The error is logged in the browser console for debugging.
React does not automatically display the error message on the page, nor does it silently ignore the error. The entire app does not crash, but the affected component tree is unmounted.
In React 18, error boundaries must be class components that implement static getDerivedStateFromError or componentDidCatch. Functional components cannot catch errors during rendering with try/catch or hooks.
Option D correctly implements an error boundary as a class component.
class ErrorBoundary extends React.Component { state = { hasError: false }; componentDidCatch(error, info) { this.setState({ hasError: true }); } render() { if (this.state.hasError) return <div>Error caught</div>; return this.props.children; } } function Child() { throw new Error('Crash'); return <div>Child</div>; } function App() { return ( <ErrorBoundary> <Child /> </ErrorBoundary> ); }
Error boundaries must implement static getDerivedStateFromError to update state when an error occurs during rendering. componentDidCatch is for side effects like logging but does not update state automatically.
Without getDerivedStateFromError, the error boundary does not re-render with error UI.
this.state.hasError after Child throws an error?class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { console.log('Error logged'); } render() { if (this.state.hasError) return <div>Error caught</div>; return this.props.children; } } function Child() { throw new Error('Crash'); return <div>Child</div>; } function App() { return ( <ErrorBoundary> <Child /> </ErrorBoundary> ); }
The static method getDerivedStateFromError returns { hasError: true }, which updates the component state to true when an error is caught during rendering.
Error boundaries catch errors during rendering, lifecycle methods, and constructors of their child components.
They do not catch errors in event handlers or asynchronous code automatically.
They must be class components; hooks cannot create error boundaries.
Errors still appear in the browser console for debugging.