How to add Skeleton Loading in NextJS ? (original) (raw)

Last Updated : 26 Jul, 2024

**Skeleton Loading in Next.js provides a placeholder UI while content is loading, improving perceived performance and user experience. It visually represents loading elements, ensuring a smoother, more engaging application.

**Approach

To add skeleton loading in nextjs application we are going to use the react-loading-skeleton npm package. The react-loading-skeleton package helps us to add a skeleton loading anywhere in our app. So first, we will install the react-loading-skeleton package and then we will add a loading screen on our homepage.

**Steps to Create NextJS Application

**Step 1: Initialize the Nextjs App

Initialize the nextjs project using the below command and move to the project directory:

npx create-next-app gfg
cd gfg

**Step 2: Install the required package:

Now we will install the react-loading-skeleton NPM package using the below command:

npm i react-loading-skeleton

**Project Structure:

The updated dependencies in the **package.json file will be:

"dependencies": {
"next": "14.2.4",
"react": "^18",
"react-dom": "^18",
"react-loading-skeleton": "^3.4.0"
},

**Example: This example demonstrates skelton loading with the help of npm package react-loading-skeleton along with the conditional rendering.

JavaScript `

// Filename - pages/index.js

import React, { useState } from 'react' import Skeleton from 'react-loading-skeleton' import 'react-loading-skeleton/dist/skeleton.css'

export default function SkeletonLoading() { const [checked, setChecked] = React.useState(false)

const handleChange = () => {
    setChecked(!checked)
}
return (
    <div>
        <label>
            <input type='checkbox' checked={checked} onChange={handleChange} />
            Loading
        </label>
        <div>
            {checked ? (
                <Skeleton />
            ) : (
                <p>NextJs Skeleton Loading - GeeksforGeeks</p>
            )}
        </div>
    </div>
)

}

`

**Explanation: In the above example first, we are importing our Skeleton component from the installed package. After that, we are using the Skeleton component inside a new function. We are also using react hook to check the current value in the checkbox. If the checkbox is checked then we are showing our loading screen.

**Steps to run the application: Run the below command in the terminal to run the app.

npm run dev

**Output: