Learn Remix · 12/13

Performance & Caching Strategies

8 min read

Course: Remix

Topic: Performance & Caching Strategies

Hey there! Let's talk about making your Remix apps not just functional, but fast. A snappy user experience is key to keeping users happy and engaged, and a huge part of that is being smart about how and when you load data. We're going to dive into some of Remix's most powerful features for performance and caching. 🏎️

Imagine you run an online library. If every single person who wanted to read a popular book had to wait for it to be printed and delivered from the main warehouse every single time, you'd have some very unhappy readers. Caching is like having popular books already available at local branches, ready to be handed out instantly.


1. The headers Function: Controlling Browser and CDN Caching

The Problem: By default, every time a user visits a page, the server has to do all the work to generate that page again, even if the content hasn't changed. This is like re-printing that book over and over. It's repetitive, slow for the user, and puts unnecessary load on your server.

The Solution: We need a way to tell the user's browser (and any Content Delivery Networks or CDNs in between) that it's okay to save a copy of the page for a little while. In Remix, the primary tool for this is the headers function you can export from your route files.

This function allows you to set HTTP headers for a specific route. The most important header for caching is Cache-Control.

How it Works:
You simply export a headers function from your route file. This function should return an object where the keys are the header names and the values are their... well, values.

javascript
// app/routes/posts._index.jsx
import { json } from "@remix-run/node";
import { getPosts } from "~/models/post.server";

export const loader = async () => {
  const posts = await getPosts();
  // We can also return headers directly from the loader
  // for client-side navigations!
  return json(posts, {
    headers: {
      "Cache-Control": "public, max-age=60",
    },
  });
};

// This headers function controls the document request (the initial page load)
export const headers = ({ loaderHeaders }) => {
  // Here, we're just re-using the headers from the loader.
  // This is a common pattern to keep caching consistent.
  return {
    "Cache-Control": loaderHeaders.get("Cache-Control"),
  };
};

export default function Posts() {
  // ... your component code
}

Breakdown of the Example:

  • loader headers: When a user navigates to this page from another page in your app (a client-side navigation), Remix only fetches the data from the loader. The headers returned here apply to that data request.
  • headers export: When a user loads this page directly by typing the URL or refreshing (a document request), the headers function is used.
  • loaderHeaders: Remix conveniently passes the headers from your loader into the headers function, so you can easily reuse them and keep your caching strategy in one place.

This simple setup tells any browser or CDN that they can cache this page's content for 60 seconds. It's a foundational step to a much faster website.


2. Cache-Control Directives: Max-Age and Stale-While-Revalidate Explained

The Problem: Just telling the browser to cache something is a good start, but how does it know how to cache? For how long? And what happens when that time is up? We need more specific instructions.

The Solution: The Cache-Control header isn't just a single value; it's a set of instructions called "directives". Two of the most powerful and commonly used directives are max-age and stale-while-revalidate.

  • public: This directive indicates that the response can be stored by any cache, including the user's browser and shared caches like CDNs.
  • max-age=<seconds>: This tells the cache how long, in seconds, the content is considered "fresh". During this time, the browser or CDN will serve the cached version instantly without even asking your server.
  • s-maxage=<seconds>: This is similar to max-age, but it specifically applies only to shared caches (like a CDN). It will override max-age for those shared caches.
  • stale-while-revalidate=<seconds>: This is where the magic happens. This directive tells the cache: "After the content becomes stale (i.e., max-age has passed), you can still show the stale content for this many additional seconds, but please check for a new version in the background."

Real-Life Scenario:
Imagine a TV screen in a train station displaying arrival times.

  1. The screen updates its data every 60 seconds (max-age=60). For those 60 seconds, the data is fresh.
  2. After 60 seconds, the data is technically "stale".
  3. But, we add stale-while-revalidate=300. Now, for the next 5 minutes (300 seconds), if a passenger looks at the screen, they'll immediately see the slightly old data. In the background, the screen is already fetching the newest arrival times.
  4. The next passenger who looks at it a moment later will see the freshly updated information.

This provides an excellent user experience: the user almost always gets an instant response, and the data stays reasonably up-to-date.

Industry Standard Example:
This combination is a fantastic pattern for content that you want to be fast but doesn't need to be real-time.

javascript
// In your loader or headers function
export const headers = () => ({
  "Cache-Control": "public, max-age=60, s-maxage=60, stale-while-revalidate=300",
});

This tells the CDN to serve content from the cache for 60 seconds. After that, for the next 5 minutes, it will serve the stale content while revalidating in the background. The user gets a fast experience, and your server is protected from a flood of requests.


3. Prefetching Links: Loading Data Before the User Clicks

The Problem: Even with caching, there's a delay. When a user clicks a link, the browser still has to go fetch the data for the next page, which takes time. We see a loading spinner. How can we make navigations feel truly instantaneous?

The Solution: Predict the future! 🔮 Well, kind of. Remix can prefetch the resources for a page before the user actually clicks the link. It does this with the prefetch prop on the <Link> component.

How it Works:
You can tell the <Link> component when to start prefetching. The most common and effective strategy is "intent".

javascript
import { Link } from "@remix-run/react";

<Link to="/products/123" prefetch="intent">
  View Awesome Product
</Link>

With prefetch="intent", the moment a user hovers their mouse over the link or focuses on it with their keyboard, Remix springs into action. It quietly starts fetching the loader data, the JavaScript modules, and the CSS for the /products/123 page in the background.

By the time the user's brain sends the signal to their finger to click, most (or all) of the loading is already done. The navigation feels incredibly fast, almost like magic. ✨

Other prefetch options:

  • render: Prefetches as soon as the link is rendered on the page. Use this sparingly for only the most high-priority links, like your primary call-to-action button.
  • viewport: Prefetches as soon as the link enters the user's viewport. This can be great for mobile devices where there is no hover "intent".
  • none: The default behavior, no prefetching.

4. Defer and Streaming: Non-blocking Data Fetching for Faster Initial Loads

The Problem: What if your page needs data from several sources, and one of them is notoriously slow? For example, a product page might load product details quickly, but fetching user reviews from a separate, slow service could take seconds. Without a strategy, your entire page is blocked, waiting for the slowest piece of data. The user stares at a blank screen, wondering if your site is broken.

The Solution: Don't wait! Send the fast stuff first and "stream" the slow stuff in when it's ready. Remix achieves this with the defer utility in your loader and the <Await> and <Suspense> components in your UI.

How it Works:
This is like ordering food at a restaurant. A good server brings your drinks and appetizers out first while the main course is still being cooked. You get something right away and aren't left waiting for everything to be done at once.

  1. defer in the loader: Instead of await-ing your slow data promises in the loader, you pass the promises to the defer function. This tells Remix to send the HTML document to the user immediately, without waiting for those promises to resolve.
  2. <Suspense> in the component: You wrap the part of your UI that depends on the slow data with React's <Suspense> component. You provide it a fallback element, like a loading spinner or a skeleton UI, to show while the data is loading.
  3. <Await> in the component: Inside the <Suspense> block, you use Remix's <Await> component to render the final UI once the deferred promise finally resolves.

Example:

javascript
// app/routes/slow-reviews.jsx
import { defer } from "@remix-run/node";
import { Await, useLoaderData } from "@remix-run/react";
import { Suspense } from "react";
import { getFastProductDetails, getSlowProductReviews } from "~/models/product.server";

export const loader = async ({ params }) => {
  const product = await getFastProductDetails(params.id);
  const reviewsPromise = getSlowProductReviews(params.id); // SLOW! 🐢

  // We don't await reviewsPromise. We defer it!
  return defer({ product, reviews: reviewsPromise });
};

export default function ProductPage() {
  const { product, reviews } = useLoaderData();

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      
      <Suspense fallback={<p>Loading reviews...</p>}>
        <Await resolve={reviews}>
          {(resolvedReviews) => (
            <ul>
              {resolvedReviews.map((review) => (
                <li key={review.id}>{review.text}</li>
              ))}
            </ul>
          )}
        </Await>
      </Suspense>
    </div>
  );
}

This pattern dramatically improves the perceived performance. Users see the critical content of the page almost instantly, and the non-critical, slow-loading sections fill in as they become available.


Further Reading

Challenge

You are building a performance-optimized product page in a Remix application. Your task is to implement data loading, caching, and UI rendering strategies to ensure the page is fast and responsive.

Requirements:

  1. Implement the loader function:

    • It should fetch product details using the provided getProductDetails function.
    • It must also fetch user reviews using the slow getReviews function.
    • Use the defer utility to stream the promise for the reviews, preventing it from blocking the initial page load.
  2. Configure Caching with the headers function:

    • Set a Cache-Control header.
    • The policy must allow caching by public caches (browsers and CDNs).
    • Set a max-age of 10 minutes (600 seconds).
    • Set a CDN-specific s-maxage of 1 hour (3600 seconds).
    • Set a stale-while-revalidate period of 1 day (86400 seconds).
  3. Update the ProductPage Component:

    • Wrap the section that will display the reviews in a <Suspense> boundary. Provide a fallback element: <div>Loading reviews...</div>.
    • Inside the <Suspense> boundary, use the <Await> component to resolve and render the list of reviews from the deferred promise.
    • Modify the existing <Link> component at the bottom of the page to add the prefetch prop with the value "intent".

Expected result

The final code should implement the loader and headers functions correctly, and update the component to use Suspense, Await, and the prefetch prop on the Link.

typescript
// app/routes/products.$productId.tsx

import type { LoaderFunctionArgs, HeadersFunction } from "@remix-run/node";
import { json, defer } from "@remix-run/node";
import { useLoaderData, Await, Link } from "@remix-run/react";
import { Suspense } from "react";

// --- Mock Data Fetching Functions (Assume these exist) ---
async function getProductDetails(productId: string) {
  // Simulates a fast DB query
  return { id: productId, name: "Super Widget", price: 99.99 };
}

async function getReviews(productId: string) {
  // Simulates a slow API call
  await new Promise(res => setTimeout(res, 2000));
  return [
    { id: 1, author: "Jane Doe", text: "Great product!" },
    { id: 2, author: "John Smith", text: "Could be better." },
  ];
}

// --- Solution: Loader Implementation ---
export const loader = async ({ params }: LoaderFunctionArgs) => {
  const productId = params.productId!;
  const details = await getProductDetails(productId);
  const reviewsPromise = getReviews(productId);
  
  return defer({ details: details, reviews: reviewsPromise });
};

// --- Solution: Headers Function Implementation ---
export const headers: HeadersFunction = ({ loaderHeaders }) => {
  return {
    "Cache-Control": "public, max-age=600, s-maxage=3600, stale-while-revalidate=86400",
  };
};

// --- Solution: Component Implementation ---
export default function ProductPage() {
  const { details, reviews } = useLoaderData<typeof loader>();

  return (
    <div>
      <h1>{details.name}</h1>
      <p>Price: ${details.price}</p>
      
      <hr />

      <h2>Reviews</h2>
      <Suspense fallback={<div>Loading reviews...</div>}>
        <Await resolve={reviews}>
          {(resolvedReviews) => (
            <ul>
              {resolvedReviews.map((review) => (
                <li key={review.id}>
                  <strong>{review.author}:</strong> {review.text}
                </li>
              ))}
            </ul>
          )}
        </Await>
      </Suspense>
      
      <hr />
      
      <Link to="/products/related" prefetch="intent">
        View Related Products
      </Link>
    </div>
  );
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.