0
0
NextJSframework~5 mins

Loading states for data in NextJS

Choose your learning style9 modes available
Introduction

Loading states show users that data is being fetched. This helps avoid confusion and improves user experience.

When fetching data from an API to display on a page
When waiting for a server response after a user action
When loading content dynamically on scroll or navigation
When showing a placeholder while images or data load
Syntax
NextJS
import { useState, useEffect } from 'react';

function Component() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(json => {
        setData(json);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  return <div>{JSON.stringify(data)}</div>;
}

Use a loading state variable to track if data is still loading.

Show a simple message or spinner while loading is true.

Examples
Basic loading message shown while data is loading.
NextJS
const [loading, setLoading] = useState(true);

if (loading) {
  return <p>Loading data, please wait...</p>;
}
Fetch data and update loading state when done.
NextJS
useEffect(() => {
  fetch('/api/items')
    .then(res => res.json())
    .then(data => {
      setItems(data);
      setLoading(false);
    });
}, []);
Loading message with accessibility roles for screen readers.
NextJS
if (loading) {
  return <div role="status" aria-live="polite">Loading...</div>;
}
Sample Program

This component fetches a list of users from an API. While waiting, it shows "Loading users...". When data arrives, it shows the user names in a list.

NextJS
import { useState, useEffect } from 'react';

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchUsers() {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await res.json();
      setUsers(data);
      setLoading(false);
    }
    fetchUsers();
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
OutputSuccess
Important Notes

Always provide feedback to users when waiting for data.

Use semantic HTML and ARIA roles for accessibility.

Keep loading messages short and clear.

Summary

Loading states tell users data is coming.

Use a state variable to track loading.

Show a message or spinner while loading.