Error boundaries help your app stay working even when some parts have problems. They catch errors in components so the whole app doesn't crash.
Why error boundaries matter in NextJS
import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback({ error, resetErrorBoundary }) { return ( <div role="alert"> <p>Something went wrong:</p> <pre>{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </div> ); } function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => { // reset the state of your app here }} > <YourComponent /> </ErrorBoundary> ); }
Error boundaries catch errors in their child components during rendering, lifecycle methods, and constructors.
They do not catch errors inside event handlers.
import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback({ error }) { return <div>Error: {error.message}</div>; } function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback}> <MyComponent /> </ErrorBoundary> ); }
import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback({ error, resetErrorBoundary }) { return ( <div role="alert"> <p>Something went wrong:</p> <pre>{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </div> ); } function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => { // reset app state }} > <MyComponent /> </ErrorBoundary> ); }
This example shows a counter button that crashes when it reaches 3. The error boundary catches the crash and shows a friendly message with a retry button.
import React, { useState } from 'react'; import { ErrorBoundary } from 'react-error-boundary'; function BuggyCounter() { const [count, setCount] = useState(0); if (count === 3) { throw new Error('I crashed at 3!'); } return <button onClick={() => setCount(count + 1)}>Count: {count}</button>; } function ErrorFallback({ error, resetErrorBoundary }) { return ( <div role="alert"> <p>Oops! Something went wrong:</p> <pre>{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </div> ); } export default function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => { // reset logic if needed }} > <BuggyCounter /> </ErrorBoundary> ); }
Use error boundaries to prevent your whole app from crashing due to one component's error.
Always provide a fallback UI so users know something went wrong.
Resetting error boundaries helps users recover without reloading the page.
Error boundaries catch errors in parts of your app to keep it running.
They improve user experience by showing friendly messages instead of broken screens.
Use them to isolate errors and allow recovery with reset options.