Loading & Error UI in Next.js

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?
Ans: It displays a loading UI while a page loads.
Q 2: What is error.js?
Ans: It handles runtime errors in a route segment.
Q 3: Are loading states automatic?
Ans: Yes, when using async components.
Q 4: Can loading UI be customized?
Ans: Yes, fully customizable.
Q 5: Does error UI support retry?
Ans: Yes, using the reset() function.

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?






Related Loading & Error UI in Next.js Topics