Error Boundary Component in Next.js
Provide an example of using an error boundary component in Next.js to gracefully handle JavaScript errors in parts of the component tree.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so next render will show fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can log the error to an error reporting service
console.error('Uncaught error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
This code defines an ErrorBoundary component using a React class component. It uses the getDerivedStateFromError method to set the error state, and componentDidCatch to log errors. When an error is caught, it renders a fallback UI.
import ErrorBoundary from './components/ErrorBoundary'; // Assuming ErrorBoundary is in the components folder
function MyApp({ Component, pageProps }) {
return (
<ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>
);
}
export default MyApp;
This code wraps the main application component inside the ErrorBoundary component to catch any errors in the app's component tree and provide a fallback UI instead of crashing the app.