## 缓存重复的函数调用
当同一函数在渲染过程中被多次传入相同参数调用时,使用模块级的 Map 来缓存函数结果。
**错误做法(冗余计算):**
typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
{projects.map(project => {
// slugify() 对相同的项目名称调用了 100 多次
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 组件中。
参考链接: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)