0 day streak
javascript / intermediate
Snippet

Handling Runtime Errors with error.tsx

In Next.js, the error.tsx file acts as a React Error Boundary. It catches unexpected errors in its segment and sub-segments, allowing you to display a fallback UI instead of crashing the entire app.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use client';
import { useEffect } from 'react';
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}
nextjs
Breakdown
1
'use client';
Error boundaries must be Client Components as they interact with the browser's error events.
2
reset: () => void
A function that prompts the segment to attempt to re-render, which can resolve temporary issues.