DEV Community

Arhan Khan
Arhan Khan

Posted on

LocalStorage for Beginners: Save Data in the Browser

LocalStorage is the browser's simplest database: a key-value store that survives page reloads and browser restarts, with no server and no setup. A reading list, a theme choice, a draft that should not vanish when the tab closes — all of these are localStorage jobs.

The API is four methods. Save a string with setItem, read it with getItem, remove it with removeItem, and clear everything with clear:

localStorage.setItem("username", "arhan");
const name = localStorage.getItem("username"); // "arhan"
localStorage.removeItem("username");
Enter fullscreen mode Exit fullscreen mode

LocalStorage only stores strings, so objects need JSON.stringify on the way in and JSON.parse on the way out:

function saveReadingList(books) {
  localStorage.setItem("reading-list", JSON.stringify(books));
}

function loadReadingList() {
  const saved = localStorage.getItem("reading-list");
  return saved ? JSON.parse(saved) : [];
}
Enter fullscreen mode Exit fullscreen mode

A complete reading-list app is a few dozen lines. Load the saved list on start, add a book, remove one, and save after every change:

let books = loadReadingList();

function addBook(title) {
  books.push({ title, done: false });
  saveReadingList(books);
  render();
}

function toggleBook(index) {
  books[index].done = !books[index].done;
  saveReadingList(books);
  render();
}

function render() {
  document.getElementById("list").innerHTML = books
    .map(
      (book, i) =>
        `<li><label><input type="checkbox" ${
          book.done ? "checked" : ""
        } onchange="toggleBook(${i})"> ${book.title}</label></li>`
    )
    .join("");
}
Enter fullscreen mode Exit fullscreen mode

If you need books to fill the list, start with these 15 best self-help books in Hindi — add a few to your reading list and try the app with real titles instead of placeholders.

Three limits to know. First, the quota is about 5MB per origin — plenty for settings and lists, not for files. Second, everything is stored as plain text and readable by any script on your site, so never store passwords or tokens. Third, localStorage is synchronous, so writing huge objects on every keystroke will freeze the page — save on a button click or debounce the save.

The companion is sessionStorage, which has the same API but clears when the tab closes — the right choice for data that should not outlive the session, like a multi-step form in progress.

Ways to extend it: add a "last saved" timestamp and show it in the UI, store the user's theme choice and apply it before the page paints to avoid a flash, or build a notes app where each note auto-saves with a 500ms debounce. LocalStorage is small, but it is the foundation every offline-first feature is built on.

Top comments (0)