0
0
NextJSframework~10 mins

Loading states for data in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Loading states for data
Component mounts
Start fetching data
Show loading state
Data fetch resolves
If success
Show data
If error
Show error message
User sees updated UI
When a component loads, it starts fetching data and shows a loading message. Once data arrives, it updates the UI or shows an error if fetching fails.
Execution Sample
NextJS
import { useState, useEffect } from 'react';

export default function DataLoader() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then(res => {
        if (!res.ok) {
          throw new Error('Network response was not ok');
        }
        return res.json();
      })
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
This React component fetches data on mount, shows "Loading..." while waiting, then displays the data once loaded or an error message if fetching fails.
Execution Table
StepActionState BeforeState AfterUI Rendered
1Component mountsloading: true, data: null, error: nullloading: true, data: null, error: null"Loading..." shown
2Fetch startsloading: true, data: null, error: nullloading: true, data: null, error: null"Loading..." shown
3Fetch resolves with dataloading: true, data: null, error: nullloading: false, data: {items: [...]}, error: nullData JSON shown
4Component re-rendersloading: false, data: {items: [...]}, error: nullloading: false, data: {items: [...]}, error: nullData JSON shown
5No more updatesloading: false, data: {items: [...]}, error: nullloading: false, data: {items: [...]}, error: nullData JSON shown
💡 Data loaded and loading set to false, so loading state ends and data is displayed.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
loadingtruetruefalsefalse
datanullnull{items: [...]}{items: [...]}
errornullnullnullnull
Key Moments - 2 Insights
Why does the UI show "Loading..." first before showing data?
Because the loading state is true initially (see execution_table step 1), so the component renders the loading message until data arrives.
What triggers the component to re-render and show the data?
When setLoading(false) and setData(...) are called after fetch resolves (step 3), React updates state causing a re-render (step 4) to show data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'loading' after step 3?
Anull
Btrue
Cfalse
Dundefined
💡 Hint
Check the 'State After' column for step 3 in the execution_table.
At which step does the UI switch from showing "Loading..." to showing the data?
AStep 1
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'UI Rendered' column in the execution_table to see when data is shown.
If the fetch never resolves, what will the UI show according to the execution flow?
A"Loading..." forever
BData JSON
CError message
DBlank screen
💡 Hint
Refer to the concept_flow where loading state shows until data arrives or error occurs.
Concept Snapshot
Loading states in Next.js:
- Start with loading=true and data=null
- Fetch data inside useEffect on mount
- Show loading UI while loading is true
- On fetch success, set data and loading=false
- Component re-renders to show data
- Always handle loading and error states for good UX
Full Transcript
This example shows how a Next.js React component manages loading states when fetching data. Initially, the component sets loading to true and data to null. When the component mounts, it starts fetching data asynchronously. While waiting, it renders a loading message. Once the fetch resolves successfully, it updates the data state and sets loading to false. This triggers a re-render, and the component then displays the fetched data. The execution table traces each step, showing state changes and UI updates. Key moments clarify why loading shows first and what triggers the data display. The visual quiz tests understanding of state values and UI changes during the process.