LocalStorage, SessionStorage In JavaScript

LocalStorage, SessionStorage In JavaScript

In JavaScript, LocalStorage and SessionStorage are part of the Web Storage API. They provide ways to store data in the browser that can persist across page reloads (LocalStorage) or only for the duration of the session (SessionStorage).

Overview: LocalStorage and SessionStorage

  • LocalStorage: Data stored in localStorage persists even when the browser is closed and reopened. It's useful for storing data that should be available across sessions.
  • SessionStorage: Data stored in sessionStorage is only available for the duration of the page session. It is cleared when the browser or tab is closed.

Both localStorage and sessionStorage are key-value stores, meaning you can store data as a key (name) and a value.

LocalStorage

  • Persistence: Data persists until explicitly deleted (even after the browser is closed and reopened).
  • Storage Limit: Typically 5-10 MB (per domain).
  • Scope: Data is accessible across all tabs and windows in the same domain.

Basic Usage of LocalStorage

Setting Data
localStorage.setItem("username", "JohnDoe"); localStorage.setItem("age", "30");
Getting Data
const username = localStorage.getItem("username"); console.log(username); // "JohnDoe"
Removing Data
localStorage.removeItem("username");
Clearing All Data
localStorage.clear();
Checking if a Key Exists
if (localStorage.getItem("username") !== null) { console.log("Username exists"); }
Storing Objects

Since localStorage only supports strings, you can store objects by serializing them with JSON.stringify() and deserializing them with JSON.parse().

const user = { name: "JohnDoe", age: 30 }; // Store object localStorage.setItem("user", JSON.stringify(user)); // Retrieve object const retrievedUser = JSON.parse(localStorage.getItem("user")); console.log(retrievedUser.name); // "JohnDoe"

SessionStorage

  • Persistence: Data is only available for the duration of the page session (i.e., until the tab or browser is closed).
  • Storage Limit: Typically 5 MB (per session).
  • Scope: Data is specific to the tab or window and cannot be accessed across tabs, even if they are opened within the same browser session.

Basic Usage of SessionStorage

Setting Data
sessionStorage.setItem("username", "JohnDoe"); sessionStorage.setItem("age", "30");
Getting Data
const username = sessionStorage.getItem("username"); console.log(username); // "JohnDoe"
Removing Data
sessionStorage.removeItem("username");
Clearing All Data
sessionStorage.clear();
Storing Objects

Just like localStorage, you can store objects in sessionStorage by serializing and deserializing them.

const user = { name: "JohnDoe", age: 30 }; // Store object sessionStorage.setItem("user", JSON.stringify(user)); // Retrieve object const retrievedUser = JSON.parse(sessionStorage.getItem("user")); console.log(retrievedUser.name); // "JohnDoe"

Differences Between LocalStorage and SessionStorage

FeatureLocalStorageSessionStorage
PersistenceData persists across sessions (even after the browser is closed)Data persists only during the current session (until the tab is closed)
Storage LimitTypically 5-10 MB per domainTypically 5 MB per session
ScopeData is available across all tabs and windows of the same domainData is specific to the tab or window
ExpirationData does not expire unless explicitly removedData expires when the tab or browser is closed

Event Listeners for Storage Events

Both localStorage and sessionStorage trigger the storage event when the storage area is changed in another window or tab. This is useful when you want to synchronize data across multiple tabs.

Example: Listening to the storage Event

window.addEventListener('storage', function (e) { console.log('Storage key changed:', e.key); console.log('Old value:', e.oldValue); console.log('New value:', e.newValue); });
  • The storage event is triggered only in other tabs or windows when the storage is modified (i.e., it doesn't trigger in the same window/tab where the modification occurred).

Common Use Cases for LocalStorage and SessionStorage

  1. LocalStorage:

    • Storing user preferences (e.g., theme settings).
    • Storing authentication tokens to persist login status across sessions.
    • Storing large data sets that need to be available after the page reloads.
  2. SessionStorage:

    • Storing temporary data for a single session (e.g., form data that needs to be preserved across page reloads within a session).
    • Storing state information that should not persist beyond the tab or window session.

Example: Using LocalStorage for a Persistent Theme Preference

// Save user's theme preference function saveThemePreference(theme) { localStorage.setItem("theme", theme); } // Get user's theme preference function getThemePreference() { return localStorage.getItem("theme") || "light"; // default to light theme } // Set the theme when the page loads document.addEventListener("DOMContentLoaded", function () { const theme = getThemePreference(); document.body.classList.add(theme); }); // Toggle theme document.getElementById("toggle-theme").addEventListener("click", function () { const currentTheme = getThemePreference(); const newTheme = currentTheme === "light" ? "dark" : "light"; saveThemePreference(newTheme); document.body.classList.replace(currentTheme, newTheme); });

In this example, the user's theme preference is saved in localStorage and persists across page reloads and browser sessions.

Summary

  • LocalStorage: Data persists across page reloads and browser sessions. Use it for long-term data storage.
  • SessionStorage: Data is only available for the duration of the page session. Use it for temporary storage within a tab or window.
  • Both storage types are simple key-value stores, but with different persistence characteristics.
  • You can store and retrieve data, including objects (by serializing them with JSON.stringify() and JSON.parse()).
  • Use the storage event to synchronize data across multiple tabs/windows.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close