How to Use unstable_cache in Next.js for Caching Data
In Next.js, you use
unstable_cache to wrap a data-fetching function so its results are cached and reused, improving performance. It takes a function and an optional options object, returning a cached version of that function. This helps avoid repeated expensive calls during rendering.Syntax
The unstable_cache function wraps your data-fetching function to cache its results. It accepts two parameters:
fn: The function whose results you want to cache.options(optional): An object with settings likettl(time to live in seconds) to control cache duration.
It returns a new function that caches the output of fn.
typescript
import { unstable_cache } from 'next/cache'; const cachedFunction = unstable_cache(fn, { ttl: 60 });
Example
This example shows how to cache a simple data-fetching function that returns a greeting message. The cached function will reuse the result for 30 seconds.
typescript
import { unstable_cache } from 'next/cache'; // Original function to fetch data async function fetchGreeting(name) { console.log('Fetching greeting...'); return `Hello, ${name}!`; } // Wrap with unstable_cache and set TTL to 30 seconds const cachedFetchGreeting = unstable_cache(fetchGreeting, { ttl: 30 }); // Example usage in a Next.js server component or API route export default async function handler(req, res) { const greeting = await cachedFetchGreeting('Alice'); res.status(200).json({ message: greeting }); }
Output
{"message":"Hello, Alice!"}
Common Pitfalls
Common mistakes when using unstable_cache include:
- Not awaiting the cached function if it returns a promise, causing unexpected behavior.
- Using
unstable_cacheon functions with side effects or non-deterministic outputs, which can cause stale or incorrect data. - Forgetting to set a
ttlwhen data changes often, leading to outdated cache.
Always use unstable_cache for pure functions that return consistent results for the same inputs.
typescript
/* Wrong usage: not awaiting cached function */ const cachedFn = unstable_cache(async () => { return 'data'; }); const result = await cachedFn(); // returns the data /* Correct usage: await the cached function */ const resultCorrect = await cachedFn();
Quick Reference
Tips for using unstable_cache effectively:
- Use it to cache expensive or slow data-fetching functions.
- Set
ttlto control how long cache lasts (in seconds). - Only cache pure functions without side effects.
- Always
awaitthe cached function if it returns a promise. - Use in server components or API routes for best results.
Key Takeaways
Use unstable_cache to wrap data-fetching functions for automatic caching in Next.js.
Set the ttl option to control cache duration and avoid stale data.
Only cache pure functions that return consistent results for the same inputs.
Always await the cached function if it returns a promise to get correct results.
Ideal for server components and API routes to improve performance.