Bird
Raised Fist0
NextJSframework~8 mins

Loading states for data in NextJS - Performance & Optimization

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
Performance: Loading states for data
MEDIUM IMPACT
This concept affects how quickly users see feedback during data fetching, impacting perceived load speed and interaction responsiveness.
Displaying feedback while waiting for data to load
NextJS
import { useState, useEffect } from 'react';

export default function Page() {
  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 <div role="status" aria-live="polite">Loading data...</div>;
  return <Content data={data} />;
}
Shows a simple loading message immediately, giving instant feedback and improving perceived responsiveness.
📈 Performance GainNon-blocking UI update; reduces INP by providing immediate visual feedback.
Displaying feedback while waiting for data to load
NextJS
export default async function Page() {
  const data = await fetch('/api/data').then(res => res.json());
  return <div>{data ? <Content data={data} /> : null}</div>;
}
No loading state shown; user sees blank or no feedback, causing poor perceived performance and possible frustration.
📉 Performance CostBlocks user feedback until data arrives, increasing INP and perceived load time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No loading stateMinimal DOM nodes0 reflows until data arrivesSingle paint delayed[X] Bad
Simple loading textFew DOM nodes1 reflow on loading displayLight paint cost[OK] Good
Rendering Pipeline
Loading states trigger style calculation and paint early, allowing the browser to show feedback before data arrives. Once data loads, layout and paint update with real content.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckPaint stage when switching from loading to content
Core Web Vital Affected
INP
This concept affects how quickly users see feedback during data fetching, impacting perceived load speed and interaction responsiveness.
Optimization Tips
1Always show a simple loading state immediately when fetching data.
2Keep loading UI lightweight to minimize paint and layout costs.
3Use ARIA roles like role="status" and aria-live="polite" for accessibility.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is showing a loading state important for data fetching in Next.js?
AIt reduces the total bundle size of the app.
BIt provides immediate feedback, improving interaction responsiveness (INP).
CIt prevents any reflows during rendering.
DIt guarantees the data loads faster from the server.
DevTools: Performance
How to check: Record a performance profile while loading the page. Look for long gaps before first paint or interaction. Check if loading UI appears quickly.
What to look for: Short time to first paint and quick visual feedback indicate good loading state implementation.

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