Do you have a vague idea of what a cache is, but want to really understand it? Want to learn how you can use caching to make your apps faster, more resilient, and even less resource-intensive for your clients? Then this article is for you.

In this article, we’re going to go through what a cache is, and what kinds of caching is relevant for most frontend developers. We’ll touch on how we can cache data in JavaScript, via service workers, the browser itself, and external caches, such as CDNs and backends. Finally, we’ll look at cache invalidation, and try to get a basic understanding of both what it is and why it’s so hard to get right.

What is a cache?

Before we dive into the many ways we can implement caching, we should look at some sort of technical definition of what a cache is. Put simply, a cache is a way to save data that you received earlier so that it’s easier to retrieve again later. I’ll explain this through an example.

Like most internet users, you’ve probably downloaded a file to your computer at some point in time. Perhaps it’s a document you’re working on with a few friends from school. Since it’s now on your computer, you can access it whenever you want, without fetching a new copy every time you want to work on it. This feature – of having access to some resources in an easier (or cheaper) way is the main idea of a cache.

We see this kind of technique used in most parts of a modern tech stack. We cache photos in our browser so they show up right away on subsequent visits. We cache the user JSON object in some sort of state management library, so we don’t have to ask the server for what the user’s name is every time we want to change what’s displayed. We even cache entire web apps in the browser so that they work without an internet connection (so-called progressive web apps or PWAs).

Why not cache everything forever, then?

With all of these upsides, you might ask yourself why we don’t cache everything forever! Why even bother fetching new data if we already have it locally? Well, as it turns out, the world isn’t static, and the data we download has the potential to change in the future. Therefore, we run the risk of dealing with out of date information whenever we cache it.

Knowing what to cache, and for how long, is one of those problems that requires you to really consider the use case of each piece of information, and how important it is to reflect changes right away. That’s why I’ve always thought of it as an art to get right. With all that said, we’ll go through some examples and give you some practical hints later on in this article.

The different types of cache

As a frontend developer, you’ll see quite a few different caching types as you progress through the stack. Here’s a description of each “layer” of cache, and when it shines.

JavaScript cache

The very first cache your code will encounter is the cache you typically make yourself. That is, some sort of way to keep the data from your API in memory.

A very simple implementation of a simple cache with no invalidation (relax, we’ll come back to what that means later) could be this:

let cache = {};
async function getCachedValue(key, callback) {
  if (cache.hasOwnProperty(key)) {
    return cache[key];
  }
  const result = await callback();
  cache[key] = result;
  return result;
}

Here, we have a “global” cache object, which is persisted between calls to this caching function. We check if the cache contains the cache key, and if it does, we simply return the cached value. If it doesn’t, we call the provided callback function to somehow get a value, place it in the cache and return it to the user.

You would then call this function with a key, and a callback that would asynchronously fetch the data in question:

const user = getCachedValue("user", async () => {
  const res = await fetch("/api/user");
  return res.json();
});

Here, we would fetch the user the first time this code was called. The second time, we would have found the user in the cache, and avoided the extra call to the server.

There are tons of libraries that help with this. I write mostly React code myself, and in that ecosystem, SWR and react-query are two great arguments that implement such a cache for you (in addition to a lot of other nice-to-have features you need).

#javascript #web-development #programming #developer

What is a Cache?
1.90 GEEK