Skip to main content

Cache persistence

A paged recipe list whose cache lives in localStorage. The API answers slowly on purpose; after a reload, every page you have already opened appears at once.

intermediatepersistencecacheuseFetch
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";

import { client, getRecipes, persistedKeys } from "./api";

const PAGE_SIZE = 6;
const pageLoadedAt = Date.now();

const Recipes = ({ page }: { page: number }) => {
// `revalidate: false` reads fresh cached data without a request. A stale or missing entry is fetched.
const { data, error, loading, responseTimestamp } = useFetch(
getRecipes.setQueryParams({
limit: PAGE_SIZE,
skip: page * PAGE_SIZE,
// `select` and `delay` are dummyjson query params: return only these fields, answer after `delay` ms.
select: "name,image,cuisine,difficulty",
// A slow response, so the difference between network and cache is easy to see.
delay: 1500,
}),
{ revalidate: false },
);

if (loading && !data) return <p aria-busy="true">Loading recipes from the network...</p>;
if (error) return <p className="error">Could not load recipes: {error.message}</p>;
if (!data) return null;

const fromStorage = responseTimestamp !== null && responseTimestamp.getTime() < pageLoadedAt;

return (
<section>
<p>
{fromStorage ? <mark>Read from localStorage</mark> : "Fetched from the network"}
<small className="muted"> · saved at {responseTimestamp?.toLocaleTimeString()}</small>
</p>
<div className="recipes">
{data.recipes.map((recipe) => (
<article key={recipe.id}>
<img src={recipe.image} alt="" loading="lazy" />
<strong>{recipe.name}</strong>
<small className="muted">
{recipe.cuisine} · {recipe.difficulty}
</small>
</article>
))}
</div>
{/* Re-read on every render of this component, which happens whenever new data arrives. */}
<details>
<summary>Persisted cache keys</summary>
<ul>
{persistedKeys().map((key) => (
<li key={key}>
<code>{key}</code>
</li>
))}
</ul>
</details>
</section>
);
};

export const App = () => {
const [page, setPage] = useState(0);

const clearAndReload = async () => {
// Removes every entry from memory and from the storage.
await client.cache.clear();
window.location.reload();
};

return (
<main className="container">
<hgroup>
<h1>Recipes</h1>
<p>Open a few pages, then reload: everything you have seen shows up at once, without a request.</p>
</hgroup>
<div className="toolbar">
<div role="group">
{[0, 1, 2].map((index) => (
<button
key={index}
type="button"
className={index === page ? undefined : "outline secondary"}
onClick={() => setPage(index)}
>
Page {index + 1}
</button>
))}
</div>
<div role="group">
<button type="button" className="secondary" onClick={() => window.location.reload()}>
Reload page
</button>
<button type="button" className="outline" onClick={clearAndReload}>
Clear persisted cache
</button>
</div>
</div>
<Recipes page={page} />
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/cache-persistence hyper-fetch-react-cache-persistence && cd hyper-fetch-react-cache-persistence && npm install && npm run dev
What it shows
  1. Cache({ storage }) replaces the in-memory Map with a storage backed by localStorage.
  2. staleTime and cacheTime decide how long persisted data is used without a request and how long it is kept.
  3. revalidate: false lets useFetch trust fresh cached data instead of fetching on every mount.
  4. cache.clear() removes the entries from memory and from the storage.

How it works​

  1. api.ts implements CacheStorageType (get, set, keys, delete, clear) on top of localStorage, with a key prefix so it only touches its own entries. Values go through JSON.stringify, so cached data must be JSON-serializable.

  2. The client receives it through the cache option:

    cache: () => new Cache({ storage: localStorageCache, version: "1" }),

    Entries saved under another version are ignored and removed, so changing it is a safe way to drop old data after a release.

  3. The storage is synchronous, so the first render after a reload already reads the saved response from it. Async storages such as IndexedDB go in lazyStorage instead and update the hooks once the read finishes.

  4. getRecipes sets staleTime: Time.MIN and cacheTime: Time.DAY. With the default cacheTime of 5 minutes, the garbage collector would remove persisted entries soon after the app starts.

  5. useFetch(..., { revalidate: false }) sends no request while the data is fresh. The label compares responseTimestamp with the page load time to show whether the data came from storage or from the network.

  6. Clear persisted cache calls client.cache.clear() and reloads, so every page is fetched again.

When to use it
  • Apps that people open often, where the last data is better than a spinner.
  • Slow or metered networks.
  • Together with the offline queue, for apps that start without a connection.

Summary

A five-method storage object passed to new Cache({ storage }) persists every cached response. staleTime, cacheTime and revalidate decide when that data is shown as is and when it is fetched again.