Home > Web Front-end > JS Tutorial > Local Storage vs Session Storage: When to Use Each (With Mini Projects)

Local Storage vs Session Storage: When to Use Each (With Mini Projects)

Barbara Streisand
Release: 2024-12-18 06:30:11
Original
111 people have browsed it

Local Storage vs Session Storage: When to Use Each (With Mini Projects)

Have you ever wondered whether you should use localStorage or sessionStorage in your web application? You’re not alone!

I’ve been there, too – wondering which of these two storage options would be ideal for my use case.

Look, web storage is not the most fascinating part of web development but it’s essential to build modern web applications that actually do something.

If you want to save user preferences, work with form data or shopping carts, you need to decide which storage method is appropriate for your use case.

I don’t want to explain all the details because it would be too much theory and sometimes theory is confusing. I will show you both storages with real code examples.

You will know when to apply which solution at the end of this post...

So stick with me!

The Basics: What You Really Need to Know

localStorage is like a notebook and sessionStorage is like a stack of sticky notes. Your notebook will remain with you until you tear out pages (clear data), while the sticky notes will be thrown away when you close your desk drawer (end session).

Here are some of the commonalities:

  • They both store data in form of key value.

  • They give you about 5-10MB of storage (depending on the browser)

  • They're synchronous and only store strings (yes, even your objects need JSON conversion)

  • They’re accessed through the same simple APIs.

Now, here’s how they differ:

localStorage:

  • Sticks around until you manually clear it

  • Persist data across browser tabs and windows

  • Don't persist something for too long (like user preferences or saved game state)

sessionStorage:

  • It disappears when you close the tab of your browser.

  • Stays isolated to the specific tab you're working in

  • Perfect for ephemeral data that shouldn't be persisted (like form state or one-time tokens)

Quick side note: Both storage types are front-end only. Don’t work with sensitive data here — it’s what secure backend storage is for.

localStorage Deep Dive

Let's face it - you probably use this storage most of the time, and for good reasons. When you need data to stick around between browser sessions, there's no better choice than with localStorage.

Best use cases for localStorage:

  • Theme preferences (dark/light mode)
  • Items in shopping cart
  • User's language setting
  • Game progress
  • Cached API responses

Quick heads up - I've seen too many developers learn these the hard way:

  • Don't store sensitive data here (it's not secure)
  • Watch out for storage limits
  • Remember to use JSON.stringify before storing
  • Be careful with expiration - localStorage doesn't expire automatically

Let me give you a concrete example with a really simple theme switcher.

const themeToggle = document.getElementById('theme-toggle');
const body = document.body;

// Check for saved theme on page load
document.addEventListener('DOMContentLoaded', () => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        body.classList.add(savedTheme);
        themeToggle.checked = savedTheme === 'dark-mode';
    }
});

// Handle theme changes
themeToggle.addEventListener('change', () => {
    if (themeToggle.checked) {
        body.classList.add('dark-mode');
        localStorage.setItem('theme', 'dark-mode');
    } else {
        body.classList.remove('dark-mode');
        localStorage.setItem('theme', 'light-mode');
    }
});
Copy after login

This code is quite simple, it will save user's preferred theme and automatically apply whenever user revisits. Nothing fancy just being practical.

sessionStorage

Sometimes you need data to stick around just for a bit - that's where sessionStorage shines.

Think of those times when you want to keep track of something until your user closes their browser tab, and not a second longer.

Perfect scenarios for sessionStorage:

  • Multi-step form data
  • Temporary authentication tokens
  • Single-session user preferences
  • Page position in a long article
  • Wizard or tutorial progress

Here's our multi-step form code that shows sessionStorage in action:

// Multi-Step Form Mini-Project
const formSteps = {
    saveStep(stepNumber, data) {
        sessionStorage.setItem(`formStep${stepNumber}`, JSON.stringify(data));
    },

    loadStep(stepNumber) {
        const savedData = sessionStorage.getItem(`formStep${stepNumber}`);
        return savedData ? JSON.parse(savedData) : null;
    },

    clearForm() {
        // Clear only our form data, not other sessionStorage items
        for (let i = 1; i <= 3; i++) {
            sessionStorage.removeItem(`formStep${i}`);
        }
    }
};

// Example usage in form steps
document.getElementById('step1-form').addEventListener('submit', (e) => {
    e.preventDefault();
    const data = {
        name: document.getElementById('name').value,
        email: document.getElementById('email').value
    };
    formSteps.saveStep(1, data);
    // Move to next step
});

// Load saved data when user returns to a step
window.addEventListener('load', () => {
    const step1Data = formSteps.loadStep(1);
    if (step1Data) {
        document.getElementById('name').value = step1Data.name;
        document.getElementById('email').value = step1Data.email;
    }
});
Copy after login

The key here is that if someone accidentally closes the tab, they'll start fresh - no stale data hanging around. But if they're just navigating between steps, their progress is safe.

Making The Right Choice

Let's cut to the chase - here's what should drive your storage decision:

Choose localStorage when:

  • Users expect their data to persist (like saved preferences)
  • You're caching data that doesn't change often
  • You need data shared between tabs
  • User convenience outweighs data freshness

Go with sessionStorage when:

  • Data should be temporary by design
  • You're handling sensitive temporary tokens
  • Each tab needs its own isolated state
  • You want a guaranteed clean slate on restart

Performance tips that actually matter:

  • Don't store massive objects - both storage types are synchronous
  • Batch your storage operations when possible
  • Remember the 5-10MB limit
  • Always handle storage errors (users might have it disabled)

Common Gotchas:

  • Always stringify objects before storing
  • Don't assume storage is available
  • Watch out for storage events in multi-tab scenarios
  • Remember to clean up old/unused data

Final thoughts: Pick the right tool for the right job. localStorage isn't always better just because it's persistent, and sessionStorage isn't always better just because it's cleaner. Think about your users' needs first.

When in doubt, ask yourself:
"Should this data survive a browser restart?"

  • Yes → localStorage
  • No → sessionStorage

That's all you need to know to make the right choice. Start building!

The above is the detailed content of Local Storage vs Session Storage: When to Use Each (With Mini Projects). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template