Consider a React component tree in a Next.js app. If a child component throws an error during rendering and there is no error boundary, what will be the visible result in the browser?
Think about what React does when an error is not caught inside the component tree.
Without an error boundary, React unmounts the entire component tree where the error happened, causing the whole UI to disappear or show a crash screen.
Why should developers use error boundaries in Next.js React components?
Think about user experience when something goes wrong in the UI.
Error boundaries catch rendering errors and display fallback UI so the rest of the app keeps working smoothly.
Given this simplified React error boundary component in Next.js, what will be rendered if a child component throws an error?
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}What does the state hasError control in the component?
When an error is caught, hasError becomes true and the fallback UI <div>Something went wrong.</div> is rendered.
Look at this error boundary code in Next.js. Why won't it catch errors thrown inside a button's onClick event?
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Error occurred</h1>;
}
return this.props.children;
}
}
function BuggyButton() {
return <button onClick={() => { throw new Error('Click error'); }}>Click me</button>;
}Think about when error boundaries work in React lifecycle.
Error boundaries only catch errors during rendering, lifecycle methods, and constructors, not in event handlers.
Next.js 14+ supports React Server Components. What is the key reason to still use error boundaries in client components?
Consider where errors happen in client vs server components.
Server components errors are handled differently; error boundaries in client components help catch UI errors on the client side and show fallback UI without crashing the whole app.