0
0
NextJSframework~5 mins

Fetch caching behavior in NextJS

Choose your learning style9 modes available
Introduction

Fetch caching helps your app load data faster by saving responses. It avoids asking the server for the same data again and again.

When you want to show data that doesn't change often, like a blog post or product details.
When you want to reduce server load by reusing data already fetched.
When you want your app to feel faster by loading cached data instantly.
When you want to control how fresh or old the data can be before fetching again.
Syntax
NextJS
fetch(url, { cache: 'default' | 'no-store' | 'force-cache' | 'only-if-cached' })

cache option controls how fetch uses the cache.

Common values: default (normal), no-store (never cache), force-cache (always use cache if available), only-if-cached (only use cache, fail if not cached).

Examples
This fetches fresh data every time, never using cache.
NextJS
fetch('/api/data', { cache: 'no-store' })
This uses cached data if available, otherwise fetches from server.
NextJS
fetch('/api/data', { cache: 'force-cache' })
Default fetch behavior, may use cache based on browser and server settings.
NextJS
fetch('/api/data')
Sample Program

This React component fetches data from an API using cache: 'force-cache'. It shows cached data if available, making loading faster.

NextJS
import React, { useEffect, useState } from 'react';

export default function CachedFetchExample() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      // Fetch with cache: 'force-cache' to use cached data if available
      const response = await fetch('/api/hello', { cache: 'force-cache' });
      const json = await response.json();
      setData(json.message);
      setLoading(false);
    }
    fetchData();
  }, []);

  if (loading) return <p>Loading...</p>;
  return <p>Message: {data}</p>;
}

// Assume /api/hello returns { "message": "Hello from API!" }
OutputSuccess
Important Notes

Using cache: 'no-store' ensures fresh data but can slow down your app.

force-cache is good for data that changes rarely.

Next.js also supports advanced caching with server actions and revalidation, but this is the basic fetch cache control.

Summary

Fetch caching controls if data is reused or freshly fetched.

Use cache option to tell fetch how to handle cache.

Choosing the right cache mode helps balance speed and data freshness.