What is the difference between localStorage and sessionStorage
· Category: JavaScript & Web
Short answer
localStorage persists data indefinitely until explicitly cleared, while sessionStorage keeps data only for the duration of the page session and isolates it by tab.
Details
Both APIs store key-value strings in the browser and share the same synchronous interface. Use localStorage for preferences, tokens, or cached content that should survive browser restarts. Use sessionStorage for multi-step form drafts or temporary state that should not leak across tabs. Because both store plain strings, serialize objects with JSON.stringify and parse them on read. Storing large payloads can block the main thread and degrade Core Web Vitals, so keep stored data minimal. If you need reactive updates across tabs, combine storage with the Broadcast Channel API instead of polling. Understanding JavaScript closures helps encapsulate storage helpers to avoid global namespace pollution.
Tips
- Do not store sensitive tokens in
localStoragewithout additional security measures; XSS can exfiltrate them. - Listen for
storageevents onwindowto detectlocalStoragechanges in other tabs. - Keep individual values under a few hundred kilobytes to prevent UI jank.