0
0
NextJSframework~30 mins

Loading states for data in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Loading states for data
📖 Scenario: You are building a simple Next.js app that fetches user data from an API. To improve user experience, you want to show a loading message while the data is being fetched.
🎯 Goal: Create a Next.js functional component that fetches user data and shows a loading message until the data is ready.
📋 What You'll Learn
Create a React functional component named UserList.
Use useState to hold the user data and loading state.
Use useEffect to fetch data from https://jsonplaceholder.typicode.com/users when the component mounts.
Show a Loading... message while fetching data.
Display the list of user names after data is loaded.
💡 Why This Matters
🌍 Real World
Loading states are common in web apps to inform users that data is being fetched, improving user experience.
💼 Career
Understanding loading states and data fetching is essential for frontend developers working with React and Next.js.
Progress0 / 4 steps
1
Set up the component and state variables
Create a React functional component called UserList. Inside it, create two state variables using useState: users initialized to an empty array, and loading initialized to true.
NextJS
Need a hint?

Use const [users, setUsers] = useState([]); and const [loading, setLoading] = useState(true); inside the component.

2
Add data fetching with useEffect
Inside the UserList component, add a useEffect hook that fetches data from https://jsonplaceholder.typicode.com/users. After fetching, update users with the data and set loading to false.
NextJS
Need a hint?

Use useEffect with an empty dependency array to fetch data once on mount. Use fetch and update states inside then.

3
Render loading message conditionally
Inside the UserList component's return statement, add JSX that shows a <p>Loading...</p> message if loading is true. Otherwise, show the list of user names.
NextJS
Need a hint?

Use a ternary operator inside JSX to show <p>Loading...</p> when loading is true, else map over users to show names.

4
Add accessibility and export the component
Ensure the ul element has an aria-label attribute with the value "User list" for accessibility. Confirm the component is exported as default.
NextJS
Need a hint?

Add aria-label="User list" to the ul element for screen readers.