0
0
NextJSframework~30 mins

Data cache behavior in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Data Cache Behavior in Next.js
📖 Scenario: You are building a simple Next.js app that fetches user data from an API. To improve performance, you want to cache the data so it doesn't fetch again on every request.
🎯 Goal: Create a Next.js component that fetches user data once and caches it using React's useState and useEffect. The component should display the user name and avoid refetching data unnecessarily.
📋 What You'll Learn
Create a state variable to store user data
Create a boolean state variable to track loading status
Use useEffect to fetch data only once when the component mounts
Display the user name after data is fetched
Avoid refetching data on re-renders
💡 Why This Matters
🌍 Real World
Caching data in React or Next.js apps improves performance by avoiding repeated network requests. This technique is common in user profile pages, dashboards, and any data-driven UI.
💼 Career
Understanding data fetching and caching is essential for frontend developers working with React and Next.js. It helps build fast, efficient, and user-friendly web applications.
Progress0 / 4 steps
1
Set up initial state variables
Create a React functional component called UserProfile. Inside it, create a state variable called user initialized to null and a state variable called loading initialized to true using useState.
NextJS
Need a hint?

Use useState(null) for user and useState(true) for loading.

2
Add API URL configuration
Inside the UserProfile component, create a constant called apiUrl and set it to https://jsonplaceholder.typicode.com/users/1.
NextJS
Need a hint?

Set apiUrl to the exact string 'https://jsonplaceholder.typicode.com/users/1'.

3
Fetch user data with useEffect and cache it
Use useEffect to fetch data from apiUrl only once when the component mounts. Inside useEffect, fetch the data, convert it to JSON, then update user with setUser and set loading to false. Use an empty dependency array [] to ensure it runs only once.
NextJS
Need a hint?

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

4
Render loading state and user name
Inside the UserProfile component's return statement, render a <div>. If loading is true, display the text Loading.... Otherwise, display the user's name inside a <h1> tag using user.name.
NextJS
Need a hint?

Use a ternary operator inside JSX to show Loading... or the user's name in an <h1>.