| 1 | --- |
| 2 | title: Cache Repeated Function Calls |
| 3 | impact: MEDIUM |
| 4 | impactDescription: avoid redundant computation |
| 5 | tags: javascript, cache, memoization, performance |
| 6 | --- |
| 7 | |
| 8 | ## Cache Repeated Function Calls |
| 9 | |
| 10 | Use 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 |
| 15 | function 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 |
| 33 | const slugifyCache = new Map<string, string>() |
| 34 | |
| 35 | function 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 | |
| 44 | function 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 |
| 61 | let isLoggedInCache: boolean | null = null |
| 62 | |
| 63 | function 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 |
| 73 | function onAuthChange() { |
| 74 | isLoggedInCache = null |
| 75 | } |
| 76 | ``` |
| 77 | |
| 78 | Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. |
| 79 | |
| 80 | Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast) |
| 81 |