| 1 | --- |
| 2 | title: Cache Storage API Calls |
| 3 | impact: LOW-MEDIUM |
| 4 | impactDescription: reduces expensive I/O |
| 5 | tags: javascript, localStorage, storage, caching, performance |
| 6 | --- |
| 7 | |
| 8 | ## Cache Storage API Calls |
| 9 | |
| 10 | `localStorage`, `sessionStorage`, and `document.cookie |
| 11 | |
| 12 | **Incorrect (reads storage on every call):** |
| 13 | |
| 14 | ```typescript |
| 15 | function getTheme() { |
| 16 | return localStorage.getItem |
| 17 | } |
| 18 | // Called 10 times = 10 storage reads |
| 19 | ``` |
| 20 | |
| 21 | **Correct (Map cache):** |
| 22 | |
| 23 | ```typescript |
| 24 | const storageCache = new |
| 25 | |
| 26 | function getLocalStorage(key: |
| 27 | if (!storageCache.has |
| 28 | storageCache.set(key |
| 29 | } |
| 30 | return storageCache.get |
| 31 | } |
| 32 | |
| 33 | function setLocalStorage(key: |
| 34 | localStorage.setItem(key |
| 35 | storageCache.set(key |
| 36 | } |
| 37 | ``` |
| 38 | |
| 39 | Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. |
| 40 | |
| 41 | **Cookie caching:** |
| 42 | |
| 43 | ```typescript |
| 44 | let cookieCache: Record |
| 45 | |
| 46 | function getCookie(name: |
| 47 | if (!cookieCache) |
| 48 | cookieCache = Object. |
| 49 | } |
| 50 | return cookieCache[name |
| 51 | } |
| 52 | ``` |
| 53 | |
| 54 | **Important (invalidate on external changes):** |
| 55 | |
| 56 | If storage can change externally (another tab, server-set cookies), invalidate cache: |
| 57 | |
| 58 | ```typescript |
| 59 | window.addEventListener("storage" |
| 60 | if (e.key |
| 61 | }); |
| 62 | |
| 63 | document.addEventListener("visibilitychange" |
| 64 | if (document.visibilityState |
| 65 | storageCache.clear(); |
| 66 | } |
| 67 | }); |
| 68 | ``` |