Local Storage and Session Storage

localStorage:

Usage:

  • localStorage stores data with no expiration time. The data will not be deleted when the browser is closed, and it will be available across browser sessions.

Example:

                                      
                                        // Storing data in localStorage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from localStorage
const storedUsername = localStorage.getItem('username');
console.log(storedUsername);  // Output: JohnDoe             
                                      
                                    

Notes:

  • Data stored in localStorage persists until explicitly removed or until the user clears their browser data.

sessionStorage:

Usage:

  • sessionStorage is similar to localStorage but has a shorter lifespan. Data stored in sessionStorage is available only for the duration of the page session. It gets cleared when the page session ends (e.g., when the browser tab is closed).

Example:

                                      
                                        // Storing data in sessionStorage
sessionStorage.setItem('theme', 'dark');

// Retrieving data from sessionStorage
const storedTheme = sessionStorage.getItem('theme');
console.log(storedTheme);  // Output: dark             
                                      
                                    

Notes:

Data stored in sessionStorage is tied to the specific tab or window where it was set.

Example: Using Web Storage for a Dark Mode Toggle:

                                      
                                        <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode Toggle</title>
    <style>
        body {
            background-color: #f4f4f4;
            color: #333;
        }
        body.dark-mode {
            background-color: #333;
            color: #fff;
        }
    </style>
</head>
<body>

    <h1>Dark Mode Toggle</h1>
    <button id="toggleButton">Toggle Dark Mode</button>

    <script>
        const toggleButton = document.getElementById('toggleButton');

        // Check if dark mode preference is stored
        const isDarkMode = localStorage.getItem('darkMode') === 'enabled';
        if (isDarkMode) {
            document.body.classList.add('dark-mode');
        }

        // Toggle dark mode on button click
        toggleButton.addEventListener('click', () => {
            const currentMode = document.body.classList.contains('dark-mode') ? 'disabled' : 'enabled';
            localStorage.setItem('darkMode', currentMode);
            document.body.classList.toggle('dark-mode');
        });
    </script>

</body>
</html>             
                                      
                                    

In this example:


  • The ‘Toggle Dark Mode’ button/returns toggles the attribute ‘dark-mode’ in the body and saves the mode in the browser localStorage.
  • On page rendering, it first looks into localStorage to determine whether the option of dark mode has been set and appear accordingly.