We’re working on a simple and powerful caching model for Next.js. In a previous post, we talked about our journey with caching and how we’ve arrived at the 'use cache' directive.
This post will discuss the API design and benefits of 'use cache' .
'use cache' makes your application faster by caching data or components as needed.
It’s a JavaScript “directive”—a string literal you add in your code—which signals to the Next.js compiler to enter a different “boundary”. For example, going from the server to the client.
This is a similar idea to React directives like 'use client' and 'use server' . Directives are compiler instructions that define where code should run, allowing the framework to optimize and orchestrate individual…
This is an excerpt. The full article is published by Next.js Blog.
Answers to common questions regarding this article's topic, architecture, and practical applications.
Let’s revisit the last example. Could we instead use a cache() function instead of a directive? function Profile({ id }) {
async function getNotifications(index, limit) {
return await cache(async () => {
return await db
.select()
.from(notifications)
.limit(limit)
.offset(index)
// Oops! Where do we include id in the cache key?
.where(eq(notifications.userId, id));
});
}
return
General
Let’s start with a simple example: async function getUser(id) {
'use cache';
let res = await fetch(`https://api.vercel.app/user/${id}`);
return res.json();
}
Behind the scenes, Next.js transforms this code into a server function due to the 'use cache' directive. During compilation, the “dependencies” of this cache entry are found and used as part of the cache key. For example, id becomes part of the cache key. If we call getUser(1) multiple
General
You can define the life of the cache with different profiles. We include a set of default profiles, but you can define your own custom values if desired. async function getUser(id) {
'use cache';
cacheLife('hours');
let res = await fetch(`https://api.vercel.app/user/${id}`);
return res.json();
}
To invalidate a specific cache entry, you can tag the cache and then call revalidateTag(). One powerful pattern is that you can tag the cache aft
General
We’re working on a simple and powerful caching model for Next.js. In a previous post, we talked about our journey with caching and how we’ve arrived at the 'use cache' directive.
Definition / Understanding
'use cache' makes your application faster by caching data or components as needed. It’s a JavaScript “directive”—a string literal you add in your code—which signals to the Next.js compiler to enter a different “boundary”. For example, going from the server to the client. This is a similar idea to React directives like 'use client' and 'use server'. Directives are compiler instructions that define where code should run, allowing the framework to o