556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / js-cache-function-results.md
1.9 KB
1--- 2title: Cache Repeated Function Calls 3impact: MEDIUM 4impactDescription: avoid redundant computation 5tags: javascript, cache, memoization, performance 6--- 7 8## Cache Repeated Function Calls 9 10Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render. 11 12**Incorrect (redundant computation):** 13 14```typescript 15function ProjectList({ projects }: { projects: Project[] }) { 16 return ( 17 <div> 18 {projects.map(project => { 19 // slugify() called 100+ times for same project names 20 const slug = slugify(project.name) 21 22 return <ProjectCard key={project.id} slug={slug} /> 23 })} 24 </div> 25 ) 26} 27``` 28 29**Correct (cached results):** 30 31```typescript 32// Module-level cache 33const slugifyCache = new Map<string, string>() 34 35function cachedSlugify(text: string): string { 36 if (slugifyCache.has(text)) { 37 return slugifyCache.get(text)! 38 } 39 const result = slugify(text) 40 slugifyCache.set(text, result) 41 return result 42} 43 44function ProjectList({ projects }: { projects: Project[] }) { 45 return ( 46 <div> 47 {projects.map(project => { 48 // Computed only once per unique project name 49 const slug = cachedSlugify(project.name) 50 51 return <ProjectCard key={project.id} slug={slug} /> 52 })} 53 </div> 54 ) 55} 56``` 57 58**Simpler pattern for single-value functions:** 59 60```typescript 61let isLoggedInCache: boolean | null = null 62 63function isLoggedIn(): boolean { 64 if (isLoggedInCache !== null) { 65 return isLoggedInCache 66 } 67 68 isLoggedInCache = document.cookie.includes('auth=') 69 return isLoggedInCache 70} 71 72// Clear cache when auth changes 73function onAuthChange() { 74 isLoggedInCache = null 75} 76``` 77 78Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. 79 80Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)