localStorage vs sessionStorage
What you'll learn: You'll discover the key differences between localStorage and sessionStorage, and when to choose each one for your data storage needs.
The Two Types of Browser Storage
Both localStorage and sessionStorage are part of the Web Storage API and work almost identically—they store key-value pairs right in the user's browser. The critical difference is how long they keep your data around.
localStorage: The Long-Term Memory
localStorage persists data indefinitely. Even if the user closes the browser tab, shuts down their computer, or comes back weeks later, the data remains until explicitly deleted by your code or the user clears browser data.
Use localStorage when:
- Saving user preferences (theme, language)
- Remembering shopping cart items between sessions
- Storing data that should survive browser restarts
sessionStorage: The Short-Term Memory
sessionStorage is tab-scoped and temporary. Data lasts only for the duration of that specific browser tab or window. When the user closes the tab, everything stored in sessionStorage for that tab vanishes completely. Even opening your site in a new tab creates a separate, empty sessionStorage.
Use sessionStorage when:
- Storing form data temporarily during a multi-step process
- Keeping authentication tokens for a single session
- Managing state that shouldn't persist between visits
The Analogy
Think of localStorage as writing in a permanent notebook that stays on your desk forever, while sessionStorage is like a whiteboard that gets erased the moment you leave the room.
Both use the exact same methods (like setItem(), getItem(), and removeItem()), so switching between them only requires changing the object name.
Key Takeaway: Use localStorage for data that should survive across browser sessions, and sessionStorage for temporary, tab-specific data that should disappear when the tab closes.