0
0
NextJSframework~30 mins

Router cache on client in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Router Cache on Client in Next.js
📖 Scenario: You are building a Next.js app that fetches user profile data from an API. To improve user experience, you want to cache the fetched data on the client side so that when users navigate back to the profile page, the app shows the cached data instantly without refetching.
🎯 Goal: Build a Next.js client component that caches user profile data after fetching it once. When the user revisits the profile page, the cached data is shown immediately. If no cached data exists, fetch from the API and then cache it.
📋 What You'll Learn
Create a React state variable to hold the user profile data
Create a cache object outside the component to store fetched data
Fetch user profile data from a mock API endpoint only if not cached
Use Next.js client component with hooks to manage state and effects
💡 Why This Matters
🌍 Real World
Caching API data on the client improves app speed and user experience by avoiding unnecessary network requests.
💼 Career
Understanding client-side caching and React hooks is essential for building efficient Next.js applications in professional web development.
Progress0 / 4 steps
1
Set up initial user profile state
Create a Next.js client component called UserProfile. Inside it, create a React state variable called profile initialized to null using useState.
NextJS
Need a hint?

Use useState(null) to create the profile state variable.

2
Create a cache object outside the component
Above the UserProfile component, create a constant object called profileCache initialized as an empty object {}. This will store cached profile data.
NextJS
Need a hint?

Define const profileCache = {} outside the component function.

3
Fetch profile data with caching logic
Inside UserProfile, use useEffect to fetch profile data from '/api/profile' only if profileCache.data is not set. If cached data exists, set profile state from cache. If not, fetch from API, update profileCache.data, and then update profile state.
NextJS
Need a hint?

Use useEffect with an empty dependency array to run once. Check profileCache.data. If it exists, set state. Otherwise, fetch and cache.

4
Render profile data or loading message
Inside the UserProfile component's return statement, render a <div>. If profile is null, show Loading profile.... Otherwise, display the user's name inside a <h1> and email inside a <p>.
NextJS
Need a hint?

Use a conditional (ternary) operator inside JSX to show loading text or profile details.