In this tutorial, you will learn how to create loading and error UI in Next.js
Loading UI (loading.js)
To show a loader, you have to add the loading.js file inside a route.
Example: Suppose, you add a loading.js file in the main section.
app/main/loading.js
Note:- It automatically shows when data is loading.
Example: Create a loading.js file
export default function Loading() {
return Loading...
;
}
Error UI (error.js)
You can use the error.js file to catch errors in a specific route.
Example: create an app/main/error.js
"use client";
export default function Error({ reset }) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try Again</button>
</div>
);
}
Benefits of Loading & Error UI in Next.js
1. No need for custom loaders.
2. Faster user experience.
3. Automatic loading states.
4. Automatic error boundaries.
Loading & Error UI in Next.js – Interview Questions
Q 1: What is loading.js?
Q 2: What is error.js?
Q 3: Are loading states automatic?
Q 4: Can loading UI be customized?
Q 5: Does error UI support retry?
Loading & Error UI in Next.js – Objective Questions (MCQs)
Q1. Which file shows a loading state during navigation?
Q2. Which file is used to handle runtime errors?
Q3. loading.js works using which React feature?
Q4. Error boundaries in Next.js are:
Q5. Which function resets an error boundary?