Both localStorage
and sessionStorage
are part of the Web Storage API and allow you to store data in the browser. However, they have key differences in lifespan and scope.
π Key Differences
Feature |
localStorage π |
sessionStorage π |
---|---|---|
Lifespan | Persists indefinitely (until manually deleted) | Expires when the tab is closed |
Scope | Shared across all tabs & windows of the same origin | Only available in the tab where it was created |
Storage Limit | ~5MB per domain | ~5MB per domain |
Availability | Even after closing/reopening the browser | Cleared when the tab is closed |
π When to Use What?
β
Use localStorage
when you need data to persist
- Store user settings, authentication tokens, or preferences.
- Example: Saving a user's theme preference (
light
ordark
).
β
Use sessionStorage
for temporary data
- Useful for tab-specific session handling.
- Example: Storing form progress that should reset when the user closes the tab.
π How to Use localStorage
πΉ Set Data
localStorage.setItem("theme", "dark");
πΉ Get Data
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"
πΉ Remove Data
localStorage.removeItem("theme");
πΉ Clear Everything
localStorage.clear();
π How to Use sessionStorage
Works just like localStorage
, but only persists until the tab is closed.
πΉ Set Data
sessionStorage.setItem("sessionID", "12345");
πΉ Get Data
const sessionID = sessionStorage.getItem("sessionID");
console.log(sessionID); // "12345"
πΉ Remove Data
sessionStorage.removeItem("sessionID");
πΉ Clear Everything
sessionStorage.clear();
π― Quick Recap
Use Case | Best Storage Option |
---|---|
Remember user preferences (e.g., theme, language) | localStorage |
Store authentication tokens (if no security concerns) | localStorage |
Track form progress (until tab closes) | sessionStorage |
Save temporary shopping cart items (only for a session) | sessionStorage |
π‘ Tip: Don't store sensitive data (e.g., passwords, API keys) in either storage, as they are accessible via JavaScript. Use HTTP-only cookies for that.
Now you know when and how to use localStorage
and sessionStorage
! π Let me know if you have any questions. π
Top comments (0)