finedaybreak/keepalive-for-react
关于
React KeepAlive is a component that can cache the state of the component and reuse it when needed.
网站与应用开发可以做什么
- Support React Router v6, v7, and v8
- Support React v16+ ~ v18+ (v19.2 Activity component support [v5.0.0])
- Support Suspense and Lazy import
- Support ErrorBoundary
实测星标增长
- 24小时
- 0
- 7天
- +1
- 15天
- +1
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.zh_CN.md
原文
React KeepAlive 组件
一个类似Vue中keep-alive的React KeepAlive组件
English | 中文
包信息
| 包名 | 版本 | 描述 |
|---|---|---|
| keepalive-for-react | 核心keepalive功能 | |
| keepalive-for-react-router | React Router集成 |
特性
- 支持 React Router v6、v7 和 v8
- 支持React v16+ ~ v18+ (v19.2 Activity component support [v5.0.0])
- 支持Suspense和懒加载导入
- 支持错误边界
- 支持自定义容器
- 支持使用className
active和inactive进行切换动画过渡 - 简单实现,无需任何额外依赖和hack方式
- 压缩后仅6KB大小
- 支持中断state Effect当组件不活动时 (v5.0.0)
注意事项
版本兼容性:
- React 18 请使用
[email protected] - React 19.2+ 请使用
keepalive-for-react@6
- React 18 请使用
请勿使用 <React.StrictMode />,它在开发模式下无法与keepalive-for-react一起工作。因为它可能会导致一些意外行为。
路由集成支持
react-router-dom@6和react-router@7/react-router@8。
安装
npm install keepalive-for-react
yarn add keepalive-for-react
pnpm add keepalive-for-react
使用
配合 React Router v6、v7 或 v8 使用
- 根据 React Router 版本安装依赖。
keepalive-for-react-router@6支持以下三个版本。
# v6
npm install react-router-dom@6 keepalive-for-react@6 keepalive-for-react-router@6
# v7
npm install react-router@7 keepalive-for-react@6 keepalive-for-react-router@6
# v8
npm install react-router@^8.3.1 keepalive-for-react@6 keepalive-for-react-router@6
React Router v8.3.1 要求 Node.js >=22.22.0,React / React DOM >=19.2.7。使用 v8 前请先更新这些依赖。
- 在项目中使用KeepAlive
import KeepAliveRouteOutlet from "keepalive-for-react-router";
function Layout() {
return (
<div className="layout">
<KeepAliveRouteOutlet />
</div>
);
}
或者
import { useMemo } from "react";
// v6
import { useLocation, useOutlet } from "react-router-dom";
// v7 / v8
// import { useLocation, useOutlet } from "react-router";
import { KeepAlive, useKeepAliveRef } from "keepalive-for-react";
function Layout() {
const location = useLocation();
const aliveRef = useKeepAliveRef();
const outlet = useOutlet();
// 确定哪个路由组件处于活动状态
const currentCacheKey = useMemo(() => {
return location.pathname + location.search;
}, [location.pathname, location.search]);
return (
<div className="layout">
<MemoizedScrollTop>
<KeepAlive transition aliveRef={aliveRef} activeCacheKey={currentCacheKey} max={18}>
<Suspense fallback={<LoadingArea />}>
<SpreadArea>{outlet}</SpreadArea>
</Suspense>
</KeepAlive>
</MemoizedScrollTop>
</div>
);
}
详情请参见 examples/react-router-dom-simple-starter
在简单标签页中
npm install keepalive-for-react
const tabs = [
{
key: "tab1",
label: "标签1",
component: Tab1,
},
{
key: "tab2",
label: "标签2",
component: Tab2,
},
{
key: "tab3",
label: "标签3",
component: Tab3,
},
];
function App() {
const [currentTab, setCurrentTab] = useState<string>("tab1");
const tab = useMemo(() => {
return tabs.find(tab => tab.key === currentTab);
}, [currentTab]);
return (
<div>
{/* ... */}
<KeepAlive transition={true} activeCacheKey={currentTab} exclude={["tab3"]}>
{tab && <tab.component />}
</KeepAlive>
</div>
);
}
详情请参见 examples/simple-tabs-starter
KeepAlive 属性
类型定义
interface KeepAliveProps {
// 确定哪个组件处于活动状态
activeCacheKey: string;
children?: KeepAliveChildren;
/**
* 最大缓存数量 默认10
*/
max?: number;
exclude?: Array<string | RegExp> | string | RegExp;
include?: Array<string | RegExp> | string | RegExp;
onBeforeActive?: (activeCacheKey: string) => void;
customContainerRef?: RefObject<HTMLDivElement>;
cacheNodeClassName?: string;
containerClassName?: string;
errorElement?: ComponentType<{
children: ReactNode;
}>;
/**
* 过渡效果 默认false
*/
transition?: boolean;
/**
* 使用view transition来过渡组件 默认false
* @see https://developer.chrome.com/docs/web-platform/view-transitions/
*/
viewTransition?: boolean;
/**
* 过渡时间 默认200ms
*/
duration?: number;
aliveRef?: RefObject<KeepAliveRef | undefined | null>;
/**
* 缓存节点最大存活时间 (秒)
* @default 0 (无限制)
*/
maxAliveTime?: number | MaxAliveConfig[];
/**
* 启用 Activity 组件 from react 19.2+
* @default false
* 注意: 如果启用 Activity 组件, useEffect 会在组件激活时触发
*/
enableActivity?: boolean;
customClassNames?: {
active?: string;
inactive?: string;
};
}
interface MaxAliveConfig {
match: string | RegExp;
expire: number;
}
自定义状态类名
customClassNames 用于自定义缓存节点的激活和非激活状态类名,默认值为 { active: "active", inactive: "inactive" }。可以只指定其中一个字段,未指定的字段沿用默认值。每个值应为单个非空 CSS 类名。
<KeepAlive activeCacheKey={currentTab} transition customClassNames={{ active: "tab-active", inactive: "tab-inactive" }}>
{children}
</KeepAlive>
自定义类名后,过渡样式中的选择器也需要使用对应名称。cacheNodeClassName 用于设置缓存节点的基础类名,与状态类名独立。
Hooks
useEffectOnActive
useEffectOnActive(() => {
console.log("active");
}, []);
useLayoutEffectOnActive
useLayoutEffectOnActive(
() => {
console.log("active");
},
[],
false,
);
// 第三个参数是可选的,默认为false,
// 如果为true,表示在首次渲染时触发useLayoutEffect时会跳过回调
useEffectOnCreate
只在组件首次创建(加入缓存)时执行一次回调,并在组件从缓存中被销毁时执行返回的清理函数。与 useEffect(fn, []) 不同,被缓存的组件再次激活时 不会 重新执行。
useEffectOnCreate(() => {
console.log("组件创建");
return () => {
console.log("组件销毁");
};
});
useLayoutEffectOnCreate
与 useEffectOnCreate 行为一致,内部使用 useLayoutEffect。适用于需要在浏览器绘制前同步执行创建逻辑的场景。
useLayoutEffectOnCreate(() => {
console.log("组件创建 (layout)");
return () => {
console.log("组件销毁 (layout)");
};
});
useKeepAliveContext
类型定义
interface KeepAliveContext {
/**
* 组件是否处于活动状态
*/
active: boolean;
/**
* 当前组件所属缓存节点的键(不一定是当前激活节点的键)
*/
cacheKey: string;
/**
* 刷新组件
* @param {string} [cacheKey] - 组件的缓存键。如果未提供,将刷新当前缓存的组件。
*/
refresh: (cacheKey?: string) => void;
/**
* 销毁组件
* @param {string} [cacheKey] - 组件的缓存键,如果未提供,将销毁调用此 Hook 的组件所属缓存节点。
*/
destroy: (cacheKey?: string | string[]) => Promise<void>;
/**
* 销毁所有组件
*/
destroyAll: () => Promise<void>;
/**
* 销毁除提供的cacheKey外的其他组件
* @param {string} [cacheKey] - 组件的缓存键。如果未提供,将保留调用此 Hook 的组件所属缓存节点,销毁其他节点。
*/
destroyOther: (cacheKey?: string) => Promise<void>;
/**
* 获取缓存节点
*/
getCacheNodes: () => Array<CacheNode>;
}
const { active, cacheKey, refresh, destroy, getCacheNodes } = useKeepAliveContext();
// cacheKey 是当前组件所属缓存节点的键
// active 是一个布尔值,true表示活动,false表示非活动
// refresh 是一个函数,你可以调用它来刷新组件
// destroy 是一个函数,你可以调用它来销毁组件
// ...
// getCacheNodes 是一个函数,你可以调用它来获取缓存节点
useKeepAliveRef
类型定义
interface KeepAliveRef {
refresh: (cacheKey?: string) => void;
destroy: (cacheKey?: string | string[]) => Promise<void>;
destroyAll: () => Promise<void>;
destroyOther: (cacheKey?: string) => Promise<void>;
getCacheNodes: () => Array<CacheNode>;
onCacheNodesChange: (callback: (cacheNodes: Array<CacheNode>) => void) => () => void;
}
onCacheNodesChange 订阅缓存节点变化(新增、更新、刷新或删除),返回取消订阅函数。支持多个监听者,各 KeepAlive 实例独立通知。订阅时不会立即调用回调;如需读取已有缓存,可调用 getCacheNodes()。在 effect 中订阅并返回清理函数:
useEffect(() => {
return aliveRef.current?.onCacheNodesChange(nodes => {
console.log(nodes);
});
}, [aliveRef]);
function App() {
const aliveRef = useKeepAliveRef();
// aliveRef.current 是一个 KeepAliveRef 对象
// 你可以在 aliveRef.current 上调用 refresh 和 destroy
aliveRef.current?.refresh();
// 通常不需要手动调用 destroy,KeepAlive 会自动处理
aliveRef.current?.destroy();
return <KeepAlive aliveRef={aliveRef}>{/* ... */}</KeepAlive>;
}
// 或者
function AppRouter() {
const aliveRef = useKeepAliveRef();
// aliveRef.current 是一个 KeepAliveRef 对象
// 你可以在 aliveRef.current 上调用 refresh 和 destroy
aliveRef.current?.refresh();
aliveRef.current?.destroy();
return <KeepAliveRouteOutlet aliveRef={aliveRef} />;
}
开发
安装依赖
pnpm install
构建包
pnpm build
探索相关项目
加载中…