| 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 |
| 16 | return ( |
| 17 | <div> |
| 18 | {projects.map(project |
| 19 | // slugify() called 100+ times for same project names |
| 20 | const slug = slugify( |
| 21 | |
| 22 | return <ProjectCard key={project.id} |
| 23 | })} |
| 24 | </div> |
| 25 | ) |
| 26 | } |
| 27 | ``` |
| 28 | |
| 29 | **Correct (cached results):** |
| 30 | |
| 31 | ```typescript |
| 32 | // Module-level cache |
| 33 | const slugifyCache = new |
| 34 | |
| 35 | function cachedSlugify(text: |
| 36 | if (slugifyCache.has |
| 37 | return slugifyCache.get |
| 38 | } |
| 39 | const result = |
| 40 | slugifyCache.set(text |
| 41 | return result |
| 42 | } |
| 43 | |
| 44 | function ProjectList({ projects |
| 45 | return ( |
| 46 | <div> |
| 47 | {projects.map(project |
| 48 | // Computed only once per unique project name |
| 49 | const slug = cachedSlugify( |
| 50 | |
| 51 | return <ProjectCard key={project.id} |
| 52 | })} |
| 53 | </div> |
| 54 | ) |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | **Simpler pattern for single-value functions:** |
| 59 | |
| 60 | ```typescript |
| 61 | let isLoggedInCache: boolean |
| 62 | |
| 63 | function isLoggedIn(): boolean |
| 64 | if (isLoggedInCache !== |
| 65 | return isLoggedInCache; |
| 66 | } |
| 67 | |
| 68 | isLoggedInCache = document. |
| 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 |