## 缓存重复的函数调用
当在渲染过程中使用相同的输入重复调用同一个函数时,使用模块级的 Map 来缓存函数结果。
**错误做法(冗余计算):**
typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
{projects.map(project => {
// 对相同的项目名称调用了 100 多次 slugify()
const slug = slugify(project.name)
return
})}
)
}
**正确做法(缓存结果):**
typescript
// 模块级缓存
const slugifyCache = new Map()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
{projects.map(project => {
// 每个唯一的项目名称仅计算一次
const slug = cachedSlugify(project.name)
return
})}
)
}
**针对单值函数的更简单模式:**
typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// 认证状态变更时清除缓存
function onAuthChange() {
isLoggedInCache = null
}
使用 Map(而非 Hook)以便在任何地方使用:工具函数、事件处理器,而不仅仅是 React 组件。
参考:[我们如何让 Vercel 仪表盘速度提升两倍](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)