Remix Client Cache 使用教程

Remix Client Cache 使用教程

remix-client-cacheUtility library to cache your client data in Remix.run项目地址:https://gitcode.com/gh_mirrors/re/remix-client-cache

项目介绍

remix-client-cache 是一个为 Remix 框架设计的强大且轻量级的客户端数据缓存库。它允许你在客户端缓存服务器加载器的数据,使用 clientLoaders 来实现。默认采用 stale-while-revalidate 策略,并在从服务器加载数据后立即替换过时信息。此外,它还支持对特定键或多个键的缓存失效,并允许你传入自定义的缓存适配器。

项目快速启动

安装

首先,通过 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: { description: Math.random() } });
};

export const clientLoader = (args: ClientLoaderFunctionArgs) => 
  cacheClientLoader(args, {
    type: "swr", // 默认是 swr,也可以设置为 normal
    key: "/user/1", // 默认是当前路由路径,包括搜索参数和哈希
    adapter: () => localStorage // 默认是内存适配器,可以是任何你希望的适配器
  });

clientLoader.hydrate = true;

应用案例和最佳实践

自定义缓存适配器

你可以使用 configureGlobalCache 函数来覆盖库的默认内存缓存适配器。这将全局切换到你提供的任何适配器:

import { configureGlobalCache } from "remix-client-cache";

configureGlobalCache(() => localStorage); // 使用 localStorage 作为缓存适配器

缓存失效

使用 useCacheInvalidator 钩子返回一个函数,可以用来使特定键的缓存失效:

import { useCacheInvalidator } from "remix-client-cache";

export default function Index() {
  const { invalidateCache } = useCacheInvalidator();
  return (
    <div>
      <button onClick={() => invalidateCache("/user/1")}>Invalidate cache</button>
    </div>
  );
}

典型生态项目

remix-client-cache 可以与以下项目结合使用,以增强缓存和性能:

  1. Remix Run: 作为 Remix 框架的一部分,提供强大的服务器和客户端渲染能力。
  2. Service Workers: 用于更高级的缓存策略和离线支持。
  3. LocalForage: 一个提供类似 localStorage API 的库,但支持 IndexedDB、WebSQL 和 localStorage。

通过结合这些项目,你可以构建出高性能、响应迅速的 Web 应用。

remix-client-cacheUtility library to cache your client data in Remix.run项目地址:https://gitcode.com/gh_mirrors/re/remix-client-cache

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋泉律Samson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值