Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/js-cache-function-results.md
1---2title: Cache Repeated Function Calls3impact: MEDIUM4impactDescription: avoid redundant computation5tags: javascript, cache, memoization, performance6---78## Cache Repeated Function Calls910Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.1112**Incorrect (redundant computation):**1314```typescript15function ProjectList({ projects }: { projects: Project[] }) {16return (17<div>18{projects.map(project => {19// slugify() called 100+ times for same project names20const slug = slugify(project.name)2122return <ProjectCard key={project.id} slug={slug} />23})}24</div>25)26}27```2829**Correct (cached results):**3031```typescript32// Module-level cache33const slugifyCache = new Map<string, string>()3435function cachedSlugify(text: string): string {36if (slugifyCache.has(text)) {37return slugifyCache.get(text)!38}39const result = slugify(text)40slugifyCache.set(text, result)41return result42}4344function ProjectList({ projects }: { projects: Project[] }) {45return (46<div>47{projects.map(project => {48// Computed only once per unique project name49const slug = cachedSlugify(project.name)5051return <ProjectCard key={project.id} slug={slug} />52})}53</div>54)55}56```5758**Simpler pattern for single-value functions:**5960```typescript61let isLoggedInCache: boolean | null = null6263function isLoggedIn(): boolean {64if (isLoggedInCache !== null) {65return isLoggedInCache66}6768isLoggedInCache = document.cookie.includes('auth=')69return isLoggedInCache70}7172// Clear cache when auth changes73function onAuthChange() {74isLoggedInCache = null75}76```7778Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.7980Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)81