Back to JavaScript Performance

Cache Storage API Calls

javascriptlocalStoragestoragecachingperformance
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

Direct access to browser-based storage like localStorage and document.cookie involves synchronous I/O operations that block the main thread and degrade performance when invoked frequently. This skill implements an in-memory caching layer using Maps or plain objects to intercept storage requests. By keeping a local mirror of frequently accessed data, the application eliminates redundant disk or browser process overhead. The implementation maintains consistency by synchronizing writes to both the persistent store and the local cache. Crucially, the pattern includes lifecycle listeners that flush or invalidate stale cache entries when external events occur, such as changes from other browser tabs or document visibility transitions. This approach creates a high-performance intermediary, ensuring that repetitive read operations execute at memory speeds while remaining compatible with non-React utility scripts.

When to Use This Skill

  • Retrieving user configuration settings from localStorage during rendering
  • Accessing session identifiers or authentication tokens from cookies
  • Managing application state that is backed by browser persistence
  • Reducing expensive disk I/O in high-frequency event handlers

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Optimize my localStorage calls to reduce latency
  • How do I cache cookies in memory to avoid repetitive reading?
  • Implement an in-memory cache for document.cookie
  • Make my storage access faster in vanilla JavaScript
  • Prevent synchronous storage blocking in my utility functions

What this skill does

  • Intercepts synchronous storage reads to prevent main-thread blocking
  • Maintains synchronization between persistent storage and in-memory cache
  • Automates cache invalidation via the storage event listener
  • Clears stale data during visibilitychange events
  • Supports universal access across React and vanilla JavaScript modules

When not to use it

  • When data is too large for the browser's available memory
  • When immediate consistency across multiple browser instances is required without external validation
  • When the data changes more frequently than it is read

Example workflow

  1. Define a persistent Map object within the module scope
  2. Create a wrapper function to fetch data from the Map first
  3. Perform a fallback read from storage only upon a cache miss
  4. Update the Map whenever a write operation is performed
  5. Register a storage event listener to clear entries when external changes occur
  6. Attach a visibilitychange handler to reset the cache upon page reactivation

Prerequisites

  • Basic understanding of browser storage APIs
  • Knowledge of JavaScript event listeners

Pitfalls & limitations

  • !Stale cache entries if updates occur in other tabs without event listeners
  • !Increased memory footprint if storing very large JSON objects
  • !Failure to handle cookie updates initiated by server-side headers

FAQ

Why use a Map instead of React state?
A Map resides in module scope, allowing it to be accessed by non-component utilities, event handlers, and shared modules without passing props.
Does this approach guarantee data accuracy?
It ensures synchronization as long as all writes go through your setter functions and you properly handle storage events for cross-tab updates.
Is this safe for sensitive data like tokens?
While it improves performance, the data is stored in plain memory; ensure you are not violating security protocols by holding sensitive tokens longer than necessary.
What happens if I forget the visibilitychange listener?
Your cache may become permanently out of sync with external changes made while the user was interacting with other browser tabs.

How it compares

Generic prompts often suggest simple caching without lifecycle handling; this skill provides a robust architectural pattern that specifically addresses stale data and synchronization edge cases.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## Cache Storage API Calls

localStorage, sessionStorage, and document.cookie are synchronous and expensive. Cache reads in memory.

**Incorrect (reads storage on every call):**

function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads


**Correct (Map cache):**

const storageCache = new Map<string, string | null>()

function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}

function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}


Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.

**Cookie caching:**

let cookieCache: Record<string, string> | null = null

function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}


**Important (invalidate on external changes):**

If storage can change externally (another tab, server-set cookies), invalidate cache:

window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})

document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/js-cache-storage/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/vercel-labs/agent-skills/js-cache-storage/SKILL.md
  • Cursor: ~/.cursor/skills/vercel-labs/agent-skills/js-cache-storage/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-cache-storage/SKILL.md

🚀 Install with CLI:
npx skills add vercel-labs/agent-skills

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid javascript performance issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under JavaScript Performance and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.