I am looking at examples about error boundaries for Next.JS components in the documentation.
'use client' // Error boundaries must be Client Components
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
I understand that error boundaries must be client side, but what I am not so sure is why the console.error()
function is wrapped in a useEffect()
function. Why not just have the console.error()
function directly inside the default exported function since it still gets called every render anyway? The only difference I have noticed is that while running the development server, I get less error logs when wrapping in the useEffect()
function.
Ideally, Side Effects are supposed to be written inside useEffect
callbacks.
A side effect is anything that changes the state of a system outside your ErrorBoundary component. console.log
is considered a side effect because it is updating the browser's console. It is an external entity to your component Error
.
Read How is printing to the console a side effect
Also, it is worth mentioning that depending on your policy, you might not want to log the same error multiple times and only when the error
actually changes.