Bird
Raised Fist0
NextJSframework~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main purpose of a loading state in a Next.js component?
easy
A. To speed up the data fetching process automatically
B. To show users that data is being fetched and the app is working
C. To permanently hide the data from users
D. To prevent users from clicking buttons

Solution

  1. Step 1: Understand loading state purpose

    Loading states inform users that data is being fetched and the app is busy.
  2. Step 2: Compare options

    Only To show users that data is being fetched and the app is working correctly describes this purpose; others are incorrect or unrelated.
  3. Final Answer:

    To show users that data is being fetched and the app is working -> Option B
  4. Quick Check:

    Loading state = user feedback [OK]
Hint: Loading states show progress to users [OK]
Common Mistakes:
  • Thinking loading states speed up data fetching
  • Confusing loading state with error state
  • Ignoring user feedback during data fetch
2. Which of the following is the correct way to declare a loading state using React hooks in a Next.js component?
easy
A. const loading = useState(false);
B. let loading = true;
C. var loading = useState(true);
D. const [loading, setLoading] = useState(false);

Solution

  1. Step 1: Identify correct useState syntax

    useState returns an array with state and setter, so destructuring is needed.
  2. Step 2: Check options

    const [loading, setLoading] = useState(false); correctly uses array destructuring; others misuse useState or declare variables incorrectly.
  3. Final Answer:

    const [loading, setLoading] = useState(false); -> Option D
  4. Quick Check:

    useState syntax = destructuring [OK]
Hint: useState returns [state, setter], use array destructuring [OK]
Common Mistakes:
  • Not destructuring useState result
  • Using var or let instead of const
  • Assigning useState directly to a variable
3. Given this Next.js component snippet, what will be rendered initially?
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    setTimeout(() => {
      setData('Hello World');
      setLoading(false);
    }, 1000);
  }, []);

  if (loading) return <div>Loading...</div>;
  return <div>{data}</div>;
}
medium
A. Nothing renders
B. <div>Hello World</div>
C. <div>Loading...</div>
D. Error: data is null

Solution

  1. Step 1: Check initial state values

    loading is true initially, so the component returns the loading message.
  2. Step 2: Understand useEffect timing

    Data and loading update after 1 second, so initially only loading message shows.
  3. Final Answer:

    <div>Loading...</div> -> Option C
  4. Quick Check:

    Initial loading = true means show loading [OK]
Hint: Initial loading true means show loading message first [OK]
Common Mistakes:
  • Assuming data shows immediately
  • Ignoring initial loading state
  • Expecting error when data is null
4. Identify the bug in this Next.js loading state code:
import { useState, useEffect } from 'react';

export default function Fetcher() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);

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

  if (loading) return <div>Loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
}
medium
A. Initial loading state should be true, not false
B. Missing dependency array in useEffect
C. setLoading(true) should be after fetch
D. fetch call is missing await keyword

Solution

  1. Step 1: Check initial loading state

    Loading starts false, but fetch begins immediately, so UI may skip loading message.
  2. Step 2: Understand effect of initial loading false

    Because loading is false initially, component renders data area before fetch completes, showing null or empty.
  3. Final Answer:

    Initial loading state should be true, not false -> Option A
  4. Quick Check:

    Loading true initially shows loading UI correctly [OK]
Hint: Start loading as true to show loading UI immediately [OK]
Common Mistakes:
  • Setting loading false initially hides loading UI
  • Ignoring initial state impact on render
  • Misplacing setLoading calls
5. You want to show a loading spinner while fetching data and then display the data or an error message if fetching fails. Which approach correctly handles loading, success, and error states in a Next.js component?
hard
A. Use three state variables: loading (boolean), data (object|null), error (string|null); update them accordingly during fetch lifecycle
B. Use only one state variable for data and show loading until data is not null
C. Use loading state only and ignore errors to simplify code
D. Fetch data outside component and pass as props to avoid loading states

Solution

  1. Step 1: Identify states needed for full fetch lifecycle

    Loading, data, and error states cover all cases: waiting, success, and failure.
  2. Step 2: Evaluate options

    Use three state variables: loading (boolean), data (object|null), error (string|null); update them accordingly during fetch lifecycle uses all three states properly; others miss error handling or loading feedback.
  3. Final Answer:

    Use three state variables: loading (boolean), data (object|null), error (string|null); update them accordingly during fetch lifecycle -> Option A
  4. Quick Check:

    Loading + data + error states = robust UI [OK]
Hint: Track loading, data, and error separately for clear UI states [OK]
Common Mistakes:
  • Ignoring error state leads to silent failures
  • Using only data state misses loading feedback
  • Fetching data outside component loses dynamic loading UI