Bird
Raised Fist0
NextJSframework~5 mins

Data cache behavior in NextJS

Choose your learning style10 modes available
Introduction

Data cache helps your app load faster by saving information so it doesn't have to fetch it again. It makes your app feel quick and smooth.

When you want to show data that doesn't change often, like a blog post or product details.
When users visit the same page multiple times and you want to avoid waiting for data to load again.
When you want to reduce the number of requests to your server or external APIs.
When you want to improve app performance on slow internet connections.
When you want to keep data available even if the user goes offline briefly.
Syntax
NextJS
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  return {
    props: { data },
    revalidate: 10 // seconds
  }
}

getStaticProps runs at build time and caches the data for fast loading.

The revalidate option tells Next.js to update the cache after the given seconds.

Examples
This caches blog posts and refreshes the cache every 60 seconds.
NextJS
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/posts').then(res => res.json())
  return { props: { posts: data }, revalidate: 60 }
}
This fetches fresh data on every request without caching.
NextJS
export async function getServerSideProps() {
  const data = await fetch('https://api.example.com/user').then(res => res.json())
  return { props: { user: data } }
}
This uses client-side caching with SWR to keep data fresh and fast.
NextJS
import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)
  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}</div>
}
Sample Program

This React component uses Next.js with the SWR library to cache user data on the client side. It shows loading text while fetching, an error message if fetching fails, and the user info when ready.

NextJS
import useSWR from 'swr'

const fetcher = url => fetch(url).then(res => res.json())

export default function UserProfile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <p>Failed to load user data.</p>
  if (!data) return <p>Loading user data...</p>

  return <main>
    <h1>User Profile</h1>
    <p>Name: {data.name}</p>
    <p>Email: {data.email}</p>
  </main>
}
OutputSuccess
Important Notes

Next.js supports different caching methods: static generation, server-side rendering, and client-side caching.

Use revalidate in getStaticProps to keep static pages updated.

Client-side caching with SWR or React Query helps keep data fresh without full page reloads.

Summary

Data caching makes your app faster by saving and reusing data.

Next.js offers caching at build time, on each request, and on the client side.

Choose caching based on how often your data changes and how fresh it needs to be.

Practice

(1/5)
1. In Next.js, what is the main benefit of using data caching?
easy
A. It increases the size of the app bundle
B. It forces the app to fetch data on every user action
C. It disables server-side rendering
D. It makes the app faster by reusing previously fetched data

Solution

  1. Step 1: Understand what caching does

    Caching stores data so it can be reused without fetching again.
  2. Step 2: Identify the benefit in Next.js context

    Reusing data avoids repeated fetches, making the app faster.
  3. Final Answer:

    It makes the app faster by reusing previously fetched data -> Option D
  4. Quick Check:

    Data caching = faster app [OK]
Hint: Caching saves time by reusing data, not refetching [OK]
Common Mistakes:
  • Thinking caching increases app size
  • Confusing caching with disabling server rendering
  • Assuming caching forces more data fetches
2. Which Next.js function is used to fetch data at build time and cache it for static pages?
easy
A. getServerSideProps
B. getInitialProps
C. getStaticProps
D. useEffect

Solution

  1. Step 1: Recall Next.js data fetching methods

    getStaticProps fetches data at build time for static generation.
  2. Step 2: Match function to caching behavior

    getStaticProps caches data during build, unlike getServerSideProps which runs on each request.
  3. Final Answer:

    getStaticProps -> Option C
  4. Quick Check:

    Build time data fetch = getStaticProps [OK]
Hint: Static props run once at build, caching data [OK]
Common Mistakes:
  • Confusing getServerSideProps with build time fetching
  • Using useEffect which runs on client side
  • Thinking getInitialProps is for static caching
3. Consider this Next.js code snippet using getStaticProps with revalidate: 10. What happens when a user visits the page after 15 seconds since last build?
medium
A. The page triggers a background rebuild and shows cached data immediately
B. The page shows stale cached data and does not update
C. The page blocks rendering until new data is fetched
D. The page fetches data on the client side only

Solution

  1. Step 1: Understand revalidate option in getStaticProps

    revalidate sets seconds after which Next.js regenerates the page in background.
  2. Step 2: Analyze behavior after 15 seconds (greater than 10)

    Next.js serves cached page immediately and triggers background rebuild for next visitor.
  3. Final Answer:

    The page triggers a background rebuild and shows cached data immediately -> Option A
  4. Quick Check:

    revalidate triggers background rebuild = The page triggers a background rebuild and shows cached data immediately [OK]
Hint: Revalidate serves cached page, rebuilds in background [OK]
Common Mistakes:
  • Thinking page blocks rendering until rebuild
  • Assuming stale data is never updated
  • Confusing client-side fetch with static regeneration
4. You notice your Next.js page using getServerSideProps is always slow. Which caching mistake might cause this?
medium
A. Not caching data on the server or client side, causing fetch on every request
B. Setting revalidate to 0 in getStaticProps
C. Using getStaticProps instead of getServerSideProps
D. Using client-side fetching inside getServerSideProps

Solution

  1. Step 1: Identify caching behavior of getServerSideProps

    getServerSideProps runs on every request, so no built-in caching unless implemented.
  2. Step 2: Recognize impact of missing caching

    Without caching, data fetch happens every time, causing slowness.
  3. Final Answer:

    Not caching data on the server or client side, causing fetch on every request -> Option A
  4. Quick Check:

    No caching with getServerSideProps = slow page [OK]
Hint: No caching on server fetch causes slow responses [OK]
Common Mistakes:
  • Confusing getStaticProps with getServerSideProps
  • Thinking revalidate affects getServerSideProps
  • Trying client fetch inside server function
5. You want to cache user profile data that updates frequently but must show fresh info within 5 seconds. Which Next.js caching strategy fits best?
hard
A. Use getStaticProps with revalidate: 60 to regenerate every minute
B. Use getServerSideProps with server-side caching that expires after 5 seconds
C. Fetch data only on client side with no caching
D. Use getStaticProps without revalidate for static caching

Solution

  1. Step 1: Analyze data freshness requirement

    Data must update within 5 seconds, so caching must expire quickly.
  2. Step 2: Match caching strategy to freshness need

    getServerSideProps with server cache expiring after 5 seconds allows fresh data and caching.
  3. Step 3: Eliminate other options

    getStaticProps with 60s revalidate is too slow; client-only fetch lacks caching; static without revalidate never updates.
  4. Final Answer:

    Use getServerSideProps with server-side caching that expires after 5 seconds -> Option B
  5. Quick Check:

    Fast update needs server cache with short expiry [OK]
Hint: Fast-changing data needs server cache with short expiry [OK]
Common Mistakes:
  • Choosing static props with long revalidate time
  • Ignoring caching and fetching only on client
  • Using static props without revalidate for fresh data
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard