Fetch caching helps your app load data faster by saving responses. It avoids asking the server for the same data again and again.
Fetch caching behavior in 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).
fetch('/api/data', { cache: 'no-store' })
fetch('/api/data', { cache: 'force-cache' })
fetch('/api/data')
This React component fetches data from an API using cache: 'force-cache'. It shows cached data if available, making loading faster.
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!" }
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.
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.