Remix Client Cache 项目教程
1. 项目介绍
remix-client-cache
是一个为 Remix 框架设计的实用库,旨在客户端缓存服务器加载的数据。它默认使用 stale while revalidate
策略,即在数据从服务器重新加载时,先返回缓存中的旧数据,然后再更新缓存。该库还支持自定义缓存适配器,如 localStorage
、sessionStorage
和 localforage
,并且允许用户为特定键或多个键失效缓存。
2. 项目快速启动
安装
首先,通过 npm 安装 remix-client-cache
:
npm install remix-client-cache
基本使用
以下是一个使用 remix-client-cache
的基本示例,使用默认的内存适配器:
import { json, type LoaderFunctionArgs } from "@remix-run/node";
import { ClientLoaderFunctionArgs } from "@remix-run/react";
import { cacheClientLoader, useCachedLoaderData } from "remix-client-cache";
export const loader = async ({ params }: LoaderFunctionArgs) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${params.user}`);
const user = await response.json();
await new Promise((resolve) => setTimeout(resolve, 1000));
return json({
user: {
...user,
description: Math.random(),
},
});
};
// 在客户端缓存加载器数据
export const clientLoader = (args: ClientLoaderFunctionArgs) => cacheClientLoader(args);
// 确保开启客户端加载器的水合功能
clientLoader.hydrate = true;
export default function Index() {
// 数据会自动缓存,并在重新获取时热交换
const [user] = useCachedLoaderData<typeof loader>();
return (
<div>
{user.name} <hr />
{user.email} <hr />
{user.username} <hr />
{user.website} <hr />
{user.description}
</div>
);
}
3. 应用案例和最佳实践
使用自定义缓存适配器
在某些情况下,您可能希望使用自定义缓存适配器,例如使用 localStorage
或 sessionStorage
。以下是如何配置全局缓存适配器的示例:
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { configureGlobalCache } from "remix-client-cache";
// 使用 localStorage 作为缓存适配器
configureGlobalCache(() => localStorage);
startTransition(() => {
hydrateRoot(document, (
<StrictMode>
<RemixBrowser />
</StrictMode>
));
});
使用不同的缓存策略
remix-client-cache
支持不同的缓存策略,例如 staleWhileRevalidate
和 normal
。您可以通过 cacheClientLoader
的第二个参数来指定缓存策略:
export const clientLoader = (args: ClientLoaderFunctionArgs) =>
cacheClientLoader(args, {
type: "staleWhileRevalidate", // 或 "normal"
key: "/user/1", // 自定义缓存键
});
4. 典型生态项目
Remix 框架
remix-client-cache
是专为 Remix 框架设计的,因此与 Remix 框架紧密集成。Remix 是一个现代的全栈 Web 框架,专注于性能和开发者体验。
React
由于 Remix 基于 React,remix-client-cache
也与 React 生态系统兼容。您可以使用 React 的钩子和组件来进一步增强您的应用。
TypeScript
remix-client-cache
完全支持 TypeScript,提供了类型安全的 API,使您能够更轻松地编写类型安全的代码。
通过以上模块的介绍,您应该能够快速上手并使用 remix-client-cache
来优化您的 Remix 应用的性能。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考