0
0
NextJSframework~30 mins

Request memoization in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Memoization in Next.js
📖 Scenario: You are building a Next.js app that fetches user data from an API. To avoid fetching the same data multiple times during a session, you want to remember (memoize) the results of previous requests.
🎯 Goal: Create a simple Next.js component that fetches user data once and reuses the cached data on subsequent renders without making new requests.
📋 What You'll Learn
Create a function to fetch user data from a mock API
Create a cache object to store fetched data
Use memoization to return cached data if available
Display the user data in a React component
💡 Why This Matters
🌍 Real World
Memoization helps avoid repeated API calls, improving app speed and reducing server load.
💼 Career
Understanding memoization and React hooks is essential for building efficient Next.js applications.
Progress0 / 4 steps
1
Set up the user data fetch function
Create an async function called fetchUserData that returns a hardcoded object with id: 1 and name: 'Alice'.
NextJS
Need a hint?

Use an async function that returns a simple object with the exact keys and values.

2
Create a cache object for memoization
Create a constant object called cache initialized as an empty object {} to store cached user data.
NextJS
Need a hint?

Use const cache = {} to create an empty object for caching.

3
Implement memoized fetch function
Create an async function called getUserData that checks if cache.user exists. If yes, return it. Otherwise, call fetchUserData(), store the result in cache.user, and return it.
NextJS
Need a hint?

Use an if statement to check cache, await the fetch function if needed, then store and return the data.

4
Create a React component to display user data
Create a React functional component called UserProfile that uses useState and useEffect to call getUserData() once on mount and display the user's name inside a <div>.
NextJS
Need a hint?

Use useState to hold user data and useEffect to fetch it once. Show loading text if data is not ready.