File Caching Behavior
Implementing a Dynamic File Counter
In this example, we have a dynamic file counter that is not yet implemented. Our goal is to implement it by using the original version from our stock-15-caching
and copying that to the file versions. We'll be working with file-counter-cache
and file_counter_dynamic
, and we will convert them one by one.
The count comes from a local file called count.json
, which is a JSON file that contains the count.
To refresh the page automatically when the button is clicked, we will use revalidate_path
. Since we don't want to cache anything on this page.
What's happening in the code?
In our Counter
function, we read the count.json
file and put the count inside. We then create a server function called increment
using "use server"
. Inside this function, we get the initial count, add one to it, and write it out. We expire the path, and we only do this because we want the page to automatically re-render.
export default function FileCounterDynamic() {
async function increment() {
"use server";
const count = JSON.parse(fs.readFileSync("count.json", "utf8"));
count.count += 1;
fs.writeFileSync("count.json", JSON.stringify(count, null, 2));
expirePath("/file-counter-dynamic");
}
For the UI, we simply have the counter and the increment button.
The dynamic file counter works as expected when we hit the increment button. However, it didn't auto-detect that we have dynamic data in there. To fix this, simply wrap the dynamic data in a Suspense
component and import Suspense
from React.
Using Cache
Now let's take a look at the cached version of the dynamic file counter. We're currently using an unstable cache to cache the file access, but we want to improve that.
import { unstable_cacheTag as cacheTag, expireTag } from "next/cache";
...
const getCount = async () => {
"use cache";
cacheTag("counter");
const count = JSON.parse(fs.readFileSync("count.json", "utf8"));
return count.count;
};
So we can reload the page a million times, and that counts always going to remain the same until we hit that increment button, and then it's going to go up to the next value, and then again, that's going to be cached until the end of time.
All right, next up, we're going to take a look at how to handle caching when it comes to fetches. Generally speaking, you've got an XJS system connecting with a microservice set on the backend, and you're doing a lot of fetches. So how to cache those fetches is very important. We'll walk through all of those scenarios in the next video.