Lesson 21 — Error boundary
Catch errors in part of the page
If a component throws an error while rendering, React removes the whole page — a white screen. An error boundary is a class component that catches errors from the components inside it and shows a fallback instead. It needs the static method getDerivedStateFromError, which returns the new state when an error happens. Next.js gives you the same idea as an error.js file per route.
Note: Next.js pages are React components, so this preview runs your code with plain React in the browser. Next.js-only features (the file router, server rendering, data fetching on the server) are not running here — where a lesson needs them, it shows a small simulation instead.
Why it matters: one broken widget shows "Something broke" instead of taking down the whole page.
Add the static getDerivedStateFromError method so it sets err to true and the broken widget shows the fallback.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Next.js Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Next.js Foundations books — check the publication year so the examples match current versions.
Search Amazon →