Bird
Raised Fist0
NextJSframework~20 mins

Loading states for data in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Loading State Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
Identify the loading state output in a Next.js component
Consider this Next.js component that fetches user data asynchronously. What will the component render while the data is loading?
NextJS
import { useState, useEffect } from 'react';

export default function UserProfile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setUser({ name: 'Alice' });
      setLoading(false);
    }, 2000);
  }, []);

  if (loading) return <p>Loading user data...</p>;

  return <p>User: {user.name}</p>;
}
A<p>Loading user data...</p>
B<p>User: Alice</p>
C<p>No user data available</p>
D<p>Error loading user data</p>
Attempts:
2 left
💡 Hint
Think about what the component returns when the loading state is true.
state_output
intermediate
2:00remaining
What is the final rendered output after data fetch?
Given this Next.js component, what will be the rendered output after 3 seconds?
NextJS
import { useState, useEffect } from 'react';

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

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

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

  return <p>Data: {data}</p>;
}
A<p>Data: </p>
B<p>Loading...</p>
C<p>Data: Hello World</p>
D<p>Error fetching data</p>
Attempts:
2 left
💡 Hint
After the timeout, loading becomes false and data is set.
🔧 Debug
advanced
2:30remaining
Why does the loading state never end in this Next.js component?
Examine this component. Why does it keep showing the loading message forever?
NextJS
import { useState, useEffect } from 'react';

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

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

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

  return <p>Data loaded</p>;
}
AThe useEffect hook is missing a dependency array.
BThe initial state of loading should be false.
CThe fetch URL is incorrect causing an error.
DThe setLoading(false) call is missing inside the fetch then block.
Attempts:
2 left
💡 Hint
Check what happens after data is fetched.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in a Next.js loading state component?
Identify the option that will cause a syntax error when used in a Next.js component managing loading state.
Aconst [loading, setLoading] = useState(true); if (loading) return <p>Loading...</p>;
Bconst [loading, setLoading] = useState(true); if (loading) return (<p>Loading...</p>);
Cconst [loading, setLoading] = useState(true); if (loading) { return <p>Loading...</p>; }
D;>p/<...gnidaoL>p< nruter )gnidaol( fi ;)eurt(etatSesu = ]gnidaoLtes ,gnidaol[ tsnoc
Attempts:
2 left
💡 Hint
Look for missing punctuation between statements.
🧠 Conceptual
expert
3:00remaining
What is the best way to handle loading states for server-side data fetching in Next.js 14 App Router?
In Next.js 14 using the App Router, which approach correctly handles loading states for server-side data fetching in a client component?
AUse a client component with useState and useEffect to fetch data and manage loading state manually.
BUse React's Suspense with a server component that fetches data and a fallback loading UI in the client component.
CUse a server component to fetch data and pass it as props to a client component that shows a loading spinner.
DFetch data inside the client component synchronously and render loading UI conditionally.
Attempts:
2 left
💡 Hint
Next.js 14 encourages server components and React Suspense for loading states.

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