Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Next.js: how do loading.tsx and error.tsx actually work?

clock icon

asked 2 months ago

message icon

1

eye icon

669

I added loading.tsx and error.tsx to a route folder and things improved, but I don't fully understand what they wrap or why error.tsx has to be a client component.

1 Answer

They are sugar for two React features, scoped to the route segment.

loading.tsx becomes a <Suspense fallback> around the segment's page. Any async server component inside suspends, and the fallback streams to the browser immediately — which is why navigation feels instant even when the data isn't ready.

error.tsx becomes an error boundary around the same segment. It must be a client component because error boundaries rely on class-component lifecycle and state that only exist on the client. It receives error and a reset() you can call to retry:

1"use client"
2
3export default function Error({ error, reset }) {
4 return <button onClick={reset}>Try again</button>
5}
1"use client"
2
3export default function Error({ error, reset }) {
4 return <button onClick={reset}>Try again</button>
5}

Both are per-segment, so a nested route gets its own boundary and a failure there doesn't blank out the parent layout.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions