localStorage in React JS
Course: React JS Training
Topic: localStorage
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Introduction: Why Browser Storage Matters
Every time you visit a website, the browser loads HTML, CSS and JavaScript, runs the code, and builds the page you see. But the moment you close the tab or refresh the page, everything the JavaScript code kept in memory disappears. Variables, arrays, objects — all gone. If a user adds items to a to-do list and then accidentally refreshes, a plain script loses all of that work.
Web applications need a way to remember things between page loads. Think about the features you use every day:
- A shopping cart that still has your items when you come back tomorrow.
- A "dark mode" toggle that stays dark after you refresh.
- A form that remembers your preferred language.
- A to-do list that keeps your tasks even when the browser is closed.
All of these need persistent storage — a place where data survives after the page unloads. The browser provides several such places, and one of the simplest and most widely used is localStorage.
For a learner moving toward React, this topic matters even more. React components hold data in state, and state resets when a component unmounts or the page reloads. Real applications constantly combine the two: React state for the live UI, and localStorage for saving that state so it comes back on the next visit. Understanding localStorage is therefore a foundation skill, not an optional extra.
2. What Is localStorage in Simple Words
localStorage is a built-in browser feature that lets JavaScript save small pieces of data as text, directly inside the user's browser, and read them back later — even after the computer has been restarted.
Three plain-language facts describe it well:
- It lives in the browser, not on a server. The data is stored on the user's own machine, tied to the website's origin (the protocol, domain and port combined). No network request is involved in saving or reading.
- It only stores text (strings). Whatever you save — a number, a boolean, an object — is converted to a string before being stored.
- It has no expiry date. Data written to
localStorage stays there until JavaScript removes it or the user clears browser data. This is the main difference from sessionStorage, which is wiped when the tab closes.
A helpful mental model: localStorage is like a small notebook that the browser keeps for your website. Your script can write a line in the notebook, close the tab, and when the user returns next week, the line is still there. Every website gets its own separate notebook, and one site cannot read another site's notes.
3. Key Terms You Should Know
Before writing code, get comfortable with the vocabulary. These terms appear throughout the documentation and in interviews.
- Web Storage API — the overall browser API that includes both
localStorage and sessionStorage. It was introduced with HTML5 as a simpler alternative to cookies.
- Origin — the combination of protocol, domain and port, for example
https://example.com. Storage is separated per origin: https://example.com and https://shop.example.com have different notebooks.
- Key–value pair — the way data is organised. You save a value under a name (the key), and later ask for the value by that same key. Keys and values are both strings.
- Persistence — the property of data surviving after the page or browser closes.
localStorage is persistent; ordinary JavaScript variables are not.
- Quota — the maximum amount of data a website may store. Browsers typically allow around 5 MB per origin for web storage, which is generous for text but not suitable for large files.
- Serialization — converting a data structure (like an object or array) into a string so it can be stored. In JavaScript this is done with
JSON.stringify(). Reading it back is deserialization, done with JSON.parse().
- Storage event — an event the browser fires in other tabs of the same origin when one tab changes
localStorage. It lets tabs stay in sync.
4. localStorage Compared with sessionStorage and Cookies
localStorage is one of three classic ways to keep data in the browser. Choosing the right one depends on how long the data should live and how much of it there is.
| Feature | localStorage | sessionStorage | Cookies |
| Lifetime | Until deleted by code or the user | Until the tab is closed | Set expiry date, or session |
| Sent to the server with requests | No | No | Yes, automatically |
| Typical capacity | About 5 MB | About 5 MB | About 4 KB per cookie |
| Easy to use from JavaScript | Yes, simple API | Yes, same API | Harder, string parsing needed |
| Best suited for | Preferences, saved drafts, cached app data | Temporary per-tab state, form progress | Small server-readable data, session identifiers |
A quick way to decide:
- Should the data survive a browser restart? Use
localStorage.
- Should the data vanish when the tab closes? Use
sessionStorage.
- Does the server need the data on every request? Use cookies (or send it explicitly from
localStorage with the Fetch API).
Note that localStorage and sessionStorage share the exact same methods — learn one and you know both. The only difference is the lifetime of the data.
5. Syntax: Methods and Structure
localStorage is a global object available in every browser JavaScript environment. You do not create it; you simply call its methods. There are five methods and one property you will use in practice:
| Member | What it does | Example |
setItem(key, value) | Saves a value under a key | localStorage.setItem("theme", "dark") |
getItem(key) | Returns the value for a key, or null if the key does not exist | localStorage.getItem("theme") |
removeItem(key) | Deletes one key and its value | localStorage.removeItem("theme") |
clear() | Deletes all keys for the origin | localStorage.clear() |
key(index) | Returns the key name at a numeric position | localStorage.key(0) |
length | Property: how many keys are stored | localStorage.length |
A few structural rules to remember:
- Both the key and the value are stored as strings. If you pass a number, the browser converts it to a string automatically.
- Saving the same key again overwrites the old value. There is no warning and no history.
- Reading a key that was never saved returns
null — not an empty string, not an error. Always check for null.
- Keys are case-sensitive:
"Theme" and "theme" are two different keys.
6. How localStorage Works Step by Step
Here is the full life of a piece of data, from saving to reading on a later visit:
- The page runs JavaScript. Your script calls
localStorage.setItem("username", "Asha").
- The browser converts the value to a string. Numbers, booleans and other non-string values are coerced to text before saving.
- The browser writes the pair to disk, in its own storage area for your website's origin. This happens synchronously — the code after
setItem runs only after the write is done.
- The page later closes or the user navigates away. All in-memory JavaScript variables are destroyed, but the storage file on disk remains.
- On the next visit, a new script calls
localStorage.getItem("username"). The browser reads the same storage area and returns "Asha".
- The data stays until code calls
removeItem or clear, or the user clears the browser's site data.
Two practical consequences of this design are worth pausing on:
- It is synchronous. Unlike the Fetch API, there are no promises and no callbacks. Reading and writing block the script for a moment. For the small amounts of text web storage is designed for, this is fine — but avoid writing large data in a loop.
- It is per-origin. If you test on
http://localhost:3000 and later open http://localhost:5000, each port is a different origin with its own storage. Data saved in one will not appear in the other.
7. First Examples: Saving Simple Values and the String Problem
Start with the smallest useful program: save a name, read it back, and display it.
<!DOCTYPE html>
<html>
<body>
<p id="greeting"></p>
<script>
// Save a value
localStorage.setItem("username", "Asha");
// Read it back
const name = localStorage.getItem("username");
// Show it on the page
document.getElementById("greeting").textContent = "Welcome back, " + name + "!";
</script>
</body>
</html>
Output on the page:
Welcome back, Asha!
Now refresh the page. The setItem line runs again and overwrites the same value, so nothing seems dramatic yet. Comment out the setItem line and refresh — the greeting still shows Welcome back, Asha!, because the value was read from storage, not from the script. That is persistence in action.
The string problem: numbers and booleans come back as text
This is the single most common beginner mistake with localStorage. Everything comes back as a string, even if you saved a number.
// Save a number
localStorage.setItem("score", 100);
// Read it back
const score = localStorage.getItem("score");
console.log(score); // "100" (a string, not a number)
console.log(typeof score); // "string"
// This is the classic bug it causes:
console.log(score + 10); // "10010" -- string concatenation, not addition!
The value 100 was stored as the text "100". When you add 10, JavaScript joins two strings instead of adding two numbers. The fix is to convert explicitly when reading:
localStorage.setItem("score", 100);
const score = Number(localStorage.getItem("score"));
console.log(score + 10); // 110 -- correct
Booleans have the same trap, with a nastier twist, because the string "false" is truthy in JavaScript:
localStorage.setItem("isAdmin", false);
const isAdmin = localStorage.getItem("isAdmin");
console.log(typeof isAdmin); // "string"
console.log(Boolean(isAdmin)); // true -- because "false" is a non-empty string!
// Safe way: compare the string itself
const reallyAdmin = localStorage.getItem("isAdmin") === "true";
console.log(reallyAdmin); // false
Rules of thumb to carry forward:
- Numbers: wrap the read value in
Number().
- Booleans: compare with
=== "true".
- Objects and arrays: use JSON, which the next section covers properly.
8. Storing Objects and Arrays with JSON
Real applications rarely store single strings. A saved user profile, a shopping cart or a list of tasks is an object or an array. If you try to store one directly, it gets converted to a useless piece of text:
const user = { name: "Asha", city: "Pune" };
localStorage.setItem("user", user);
console.log(localStorage.getItem("user"));
// "[object Object]" -- the data is lost!
When JavaScript converts an object to a string automatically, it produces the placeholder text [object Object]. The properties are gone. The correct approach is to serialize the object yourself with JSON.stringify() before saving, and deserialize with JSON.parse() after reading.
const user = { name: "Asha", city: "Pune" };
// Serialize: object to JSON string
localStorage.setItem("user", JSON.stringify(user));
// Read the raw string
const raw = localStorage.getItem("user");
console.log(raw); // '{"name":"Asha","city":"Pune"}'
// Deserialize: JSON string back to a real object
const saved = JSON.parse(raw);
console.log(saved.name); // "Asha"
console.log(saved.city); // "Pune"
Arrays work exactly the same way:
const fruits = ["mango", "banana", "chikoo"];
localStorage.setItem("fruits", JSON.stringify(fruits));
const savedFruits = JSON.parse(localStorage.getItem("fruits"));
console.log(savedFruits[0]); // "mango"
console.log(savedFruits.length); // 3
A safe reading pattern
JSON.parse(null) returns null, which is harmless — but JSON.parse throws an error if the stored text is not valid JSON. If the data might be corrupted or was written by an older version of your app, wrap the read in a try...catch:
function loadJSON(key, fallback) {
try {
const raw = localStorage.getItem(key);
if (raw === null) {
return fallback; // key never saved: use a default
}
return JSON.parse(raw);
} catch (error) {
console.error("Could not parse stored data for key:", key);
return fallback; // corrupt data: use a default
}
}
const settings = loadJSON("settings", { theme: "light", fontSize: 14 });
console.log(settings.theme); // "light" if nothing was stored
This pattern — a helper that reads, parses and falls back to a default — is used in almost every real codebase, and it is a habit worth building early.
9. Removing and Clearing Data
Data in localStorage never expires on its own, so your code needs to know how to delete it. There are two levels of deletion:
// Remove one key
localStorage.setItem("tempToken", "abc123");
localStorage.removeItem("tempToken");
console.log(localStorage.getItem("tempToken")); // null
// Remove everything for this origin
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
localStorage.clear();
console.log(localStorage.length); // 0
Use removeItem in normal application logic — for example, deleting one completed task from a saved list. Use clear sparingly, usually in a "reset app data" button or a logout routine, because it wipes every key your site has stored, including keys written by other scripts on the same origin.
You can also inspect and delete stored data manually. Open the browser DevTools (usually F12), go to the Application tab (called Storage in some browsers), and find Local Storage in the sidebar. You will see every key and value for the current origin, and you can edit or delete them by hand. This is the fastest way to debug storage problems during development.
10. Realistic Example: Remembering a Theme Preference
A classic real-world use of localStorage is remembering a user's choice of light or dark theme. The pattern is always the same: read first, apply, then save on change.
<!DOCTYPE html>
<html>
<head>
<style>
body { background: #ffffff; color: #111111; }
body.dark { background: #111111; color: #eeeeee; }
</style>
</head>
<body>
<h3>Theme demo</h3>
<button id="toggleBtn">Toggle theme</button>
<script>
const btn = document.getElementById("toggleBtn");
function applyTheme(theme) {
document.body.classList.toggle("dark", theme === "dark");
}
// 1. On load: read the saved theme (or default to "light")
const savedTheme = localStorage.getItem("theme") || "light";
applyTheme(savedTheme);
// 2. On click: flip the theme, apply it, and save it
btn.addEventListener("click", function () {
const current = localStorage.getItem("theme") || "light";
const next = current === "dark" ? "light" : "dark";
applyTheme(next);
localStorage.setItem("theme", next);
});
</script>
</body>
</html>
What happens, step by step:
- The page loads and immediately reads
"theme". If the user has visited before, their choice is applied before they see anything flash the wrong way.
- If nothing is stored,
getItem returns null, and the || "light" fallback supplies a sensible default.
- Each click computes the opposite theme, applies it to the page, and writes it to storage.
- The user can close the browser entirely; on the next visit the saved theme is still applied.
This "read on load, save on change, fall back to a default" loop is the fundamental localStorage pattern. You will reuse it for language choices, volume sliders, sidebar positions and many other preferences.
11. Realistic Example: A To-Do List That Survives a Refresh
The theme example stored one string. Most applications need to store a collection that changes over time. This example combines everything so far: an array of tasks, JSON serialization, a safe read with a fallback, and saving after every change.
<!DOCTYPE html>
<html>
<body>
<input id="taskInput" placeholder="Add a task">
<button id="addBtn">Add</button>
<ul id="taskList"></ul>
<script>
const input = document.getElementById("taskInput");
const addBtn = document.getElementById("addBtn");
const list = document.getElementById("taskList");
// Read the saved tasks, or start with an empty array
function loadTasks() {
try {
const raw = localStorage.getItem("tasks");
return raw ? JSON.parse(raw) : [];
} catch (error) {
return [];
}
}
let tasks = loadTasks();
function saveTasks() {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
function render() {
list.innerHTML = "";
tasks.forEach(function (task, index) {
const li = document.createElement("li");
li.textContent = task;
const del = document.createElement("button");
del.textContent = "Delete";
del.addEventListener("click", function () {
tasks.splice(index, 1); // remove from the array
saveTasks(); // persist the change
render(); // redraw the list
});
li.appendChild(del);
list.appendChild(li);
});
}
addBtn.addEventListener("click", function () {
const text = input.value.trim();
if (text === "") return;
tasks.push(text);
input.value = "";
saveTasks();
render();
});
render();
</script>
</body>
</html>
Notice the clean division of responsibilities, which is the same division you will use in React later:
- The array is the source of truth. All changes go through the array, never directly into storage or the DOM.
saveTasks() is the only place that writes to localStorage.
render() is the only place that touches the DOM, and it always draws the current array.
- Every mutation (add or delete) follows the same rhythm: change the array, save, re-render.
Refresh the page after adding tasks — they are still there. Close the browser and reopen it — still there. This tiny app demonstrates the full persistence workflow that real products rely on.
12. The storage Event and Cross-Tab Communication
One subtle but useful feature: when one tab changes localStorage, the browser fires a storage event in every other open tab of the same origin. The tab that made the change does not receive the event — only its siblings do. This lets multiple tabs stay in sync without any server.
// Run this in TWO tabs of the same site, then change
// the value in one tab and watch the other react.
window.addEventListener("storage", function (event) {
console.log("Key changed: ", event.key); // "cartCount"
console.log("Old value: ", event.oldValue); // "3"
console.log("New value: ", event.newValue); // "4"
console.log("Changed in tab:", event.url);
// React to the change, for example update the UI
if (event.key === "cartCount") {
document.title = "Cart (" + event.newValue + ")";
}
});
The event object carries useful properties:
key — the key that changed (or null if clear() was called).
oldValue — the previous value, or null if the key was newly created.
newValue — the new value, or null if the key was removed.
url — the address of the page that made the change.
A common use is keeping a cart badge or a logged-in state consistent across tabs. Remember the direction: tab A writes, tabs B and C listen. If you test this with only one tab open, you will see nothing — a frequent source of confusion in the classroom.
13. Limits, Quotas and Common Pitfalls
localStorage is simple, but a handful of boundaries and mistakes cause most real-world problems. Knowing them in advance saves hours of debugging.
Size limits
Browsers give each origin roughly 5 MB of web storage (the exact figure varies slightly between browsers). That is plenty for preferences, settings and small JSON collections, but not for images, audio, large datasets or anything you would call a "file". Storing base64-encoded images in localStorage is a well-known anti-pattern — use appropriate storage or serve files over HTTP instead.
Writing beyond the quota throws an error
If the quota is exceeded, setItem throws a QuotaExceededError. In private or incognito browsing, some browsers restrict storage further and may throw on any write. Code that writes user-generated content should be prepared:
function safeSetItem(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (error) {
console.error("Saving failed:", error.name);
return false;
}
}
Pitfalls to avoid
- Forgetting that everything is a string. Always convert numbers with
Number() and handle booleans by comparing to "true", as shown earlier.
- Saving objects without JSON.
setItem("user", someObject) silently stores [object Object]. Always use JSON.stringify and JSON.parse.
- Not handling
null. Reading a missing key returns null. Calling a string method on null crashes the script, so check before using the value.
- Storing sensitive information. Data in
localStorage is readable by any script on the page, including third-party scripts. Never store passwords, tokens for sensitive operations or personal identity documents there.
- Assuming it always exists. In rare environments (some privacy modes, or storage disabled by policy) accessing
localStorage can throw. Defensive code wraps access in try...catch.
- Using it as a database. There is no querying, no indexing and no relations — just keys and strings. For structured data that grows, IndexedDB is the appropriate tool.
- Blocking the main thread with large writes. Storage operations are synchronous. Writing megabytes of JSON freezes the page while it happens. Keep entries small.
Quick reference: the core pattern in one block
// SAVE (works for any data type)
localStorage.setItem("key", JSON.stringify(value));
// READ safely, with a fallback
let value;
try {
const raw = localStorage.getItem("key");
value = raw ? JSON.parse(raw) : defaultValue;
} catch (error) {
value = defaultValue;
}
// UPDATE: read, change, save back
value.someProperty = "new value";
localStorage.setItem("key", JSON.stringify(value));
// DELETE
localStorage.removeItem("key"); // one key
localStorage.clear(); // everything for this origin
Master this block and you can implement persistence for preferences, drafts, carts and lists in any plain JavaScript project — and recognise exactly where it fits when you meet state management in React.
14. Advanced Pattern: A Storage Helper Module
As soon as more than two or three features of an app use localStorage, writing JSON.stringify and JSON.parse at every call site becomes repetitive and error-prone. Professional codebases wrap the raw API in a small helper module that handles serialization, defaults and errors in one place.
// storage.js
const storage = {
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error("Storage write failed for key:", key, error);
}
},
get(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch (error) {
console.error("Storage read failed for key:", key, error);
return fallback;
}
},
remove(key) {
localStorage.removeItem(key);
}
};
export default storage;
Using it elsewhere becomes clean and safe:
import storage from "./storage.js";
storage.set("cart", [{ id: 1, name: "Notebook", qty: 2 }]);
const cart = storage.get("cart", []);
console.log(cart[0].name); // "Notebook"
storage.remove("cart");
The benefits are easy to see:
- Serialization happens in exactly one place, so no call site can forget it.
- Every read has a fallback, so no call site crashes on a missing key.
- If the app later migrates to another storage mechanism, only this file changes.
This is also a gentle introduction to the idea of abstraction: hide the messy details behind a small, well-named interface. The same thinking applies to hooks in React, where you will soon wrap this exact logic inside a custom hook such as useLocalStorage.
15. Real-World Uses: Form Auto-Save and Search History
Two features appear in almost every modern web product and are perfect practice for localStorage: saving a half-filled form so a refresh does not destroy the user's typing, and keeping a list of recent searches.
Auto-saving a form draft
<textarea id="reply"></textarea>
<p id="status"></p>
<script>
const box = document.getElementById("reply");
const status = document.getElementById("status");
// Restore the draft on load
box.value = localStorage.getItem("draft") || "";
// Save on every keystroke
box.addEventListener("input", function () {
localStorage.setItem("draft", box.value);
status.textContent = "Draft saved";
});
</script>
If the user refreshes mid-sentence, the text comes back. When the form is finally submitted, the app calls localStorage.removeItem("draft") so the stale draft does not reappear next time.
Keeping recent searches
function addSearch(term) {
// Read the existing list, or start empty
const history = JSON.parse(localStorage.getItem("recentSearches") || "[]");
// Newest first, no duplicates, maximum five entries
const updated = [term, ...history.filter(t => t !== term)].slice(0, 5);
localStorage.setItem("recentSearches", JSON.stringify(updated));
return updated;
}
console.log(addSearch("react hooks"));
console.log(addSearch("css grid"));
console.log(addSearch("react hooks")); // moved to front, no duplicate
// ["react hooks", "css grid"]
Notice the three small techniques combined here: spreading the new term at the front, filtering out the duplicate, and slicing the array to a maximum length. This "read, transform, write back" cycle is the standard way to maintain a collection in storage.
16. Combining localStorage with the Fetch API: Caching Responses
A very practical advanced use is caching. Fetching data from an API takes time and network traffic; localStorage can remember the last response so the app can show something instantly on the next visit, then refresh in the background.
async function loadUsers() {
const cacheKey = "usersCache";
// 1. Show cached data immediately, if any
const cached = localStorage.getItem(cacheKey);
if (cached) {
renderUsers(JSON.parse(cached));
}
// 2. Fetch fresh data and update the cache
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
localStorage.setItem(cacheKey, JSON.stringify(users));
renderUsers(users); // re-render with fresh data
} catch (error) {
console.error("Network failed:", error);
// If there was no cache and the network failed, show a message
if (!cached) {
renderError("Could not load users. Please try again later.");
}
}
}
This "cache first, then refresh" strategy makes the interface feel instant and keeps the app usable on poor connections. Two cautions apply:
- Only cache responses that do not change often and are not sensitive.
- For data that must stay current, add a timestamp alongside the data and treat cached entries older than a chosen age as stale.
17. Common Mistakes and the Correct Way
Each mistake below appears constantly in beginner projects and code reviews. Learn to recognise them on sight.
Saving an object directly
// Wrong: value becomes "[object Object]"
localStorage.setItem("profile", { name: "Ravi" });
// Correct: serialize first
localStorage.setItem("profile", JSON.stringify({ name: "Ravi" }));
Trusting a stored boolean
// Wrong: "false" is a truthy string, so this branch always runs
if (localStorage.getItem("darkMode")) {
enableDarkMode();
}
// Correct: compare the string explicitly
if (localStorage.getItem("darkMode") === "true") {
enableDarkMode();
}
Doing math on a stored number
// Wrong: string concatenation gives "52"
const count = localStorage.getItem("visits");
console.log(count + 1);
// Correct: convert before calculating
const count = Number(localStorage.getItem("visits")) || 0;
console.log(count + 1); // a real number
Calling string or array methods on a missing key
// Wrong: crashes if "tasks" was never saved, because getItem returns null
const tasks = JSON.parse(localStorage.getItem("tasks"));
tasks.push("new task");
// Correct: guard against null with a fallback
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
tasks.push("new task");
Writing inside a tight loop
// Wrong: one synchronous disk write per iteration
for (let i = 0; i < 1000; i++) {
localStorage.setItem("item" + i, JSON.stringify(records[i]));
}
// Correct: build the structure in memory, write once
localStorage.setItem("records", JSON.stringify(records));
Testing the storage event in a single tab
// Wrong expectation: the tab that writes also hears the event
window.addEventListener("storage", handler);
localStorage.setItem("x", "1"); // this tab fires nothing
// Correct: open a second tab of the same origin.
// When tab A writes, only tab B receives the event.
Storing sensitive data
// Wrong: any script on the page can read this
localStorage.setItem("password", "secret123");
// Correct: keep credentials out of browser storage entirely.
// Authentication should be handled with proper server-side
// mechanisms, not with localStorage.
18. Best Practices
These guidelines separate tidy, production-quality storage code from fragile scripts.
- Namespace your keys. Prefix every key with the app name, such as
"notesapp:theme", so your keys never collide with keys written by other scripts on a shared origin.
- Centralize key names. Define them once as constants instead of scattering raw strings through the code, so a typo shows up as one clear error.
- Always serialize with JSON and read with a fallback. The
storage.get(key, fallback) pattern from earlier removes an entire class of bugs.
- Keep values small. Web storage is for preferences and small collections, not for files or large datasets.
- Write once, not in loops. Batch changes in memory and persist with a single
setItem.
- Clean up after yourself. Remove keys when the data they hold is no longer meaningful, such as a draft after submission.
- Handle the quota error. Wrap writes in
try...catch when the data comes from user input, because a full quota throws.
- Never store secrets. Treat everything in
localStorage as readable by any script running on the page.
- Version your stored data. When the shape of a saved object changes, include a version field and migrate or discard old data on load, so an app update does not crash on legacy values.
// Namespaced, centralized keys
const KEYS = {
theme: "notesapp:theme",
tasks: "notesapp:tasks",
draft: "notesapp:draft"
};
localStorage.setItem(KEYS.theme, "dark");
19. Practical Project: Study Notes App with Auto-Save
This project combines nearly everything on the page into one small, complete application: a notes editor that keeps several named notes, auto-saves as you type, remembers the last opened note, and can delete notes. Build it in five steps.
Step 1: Plan the data shape
One key, one JSON value. The stored object looks like this:
{
"lastOpened": "note-1",
"notes": [
{ "id": "note-1", "title": "JavaScript", "body": "Practise closures..." },
{ "id": "note-2", "title": "CSS Grid", "body": "grid-template-columns..." }
]
}
Step 2: Build the static structure
<!DOCTYPE html>
<html>
<body>
<h3>My Notes</h3>
<select id="notePicker"></select>
<button id="newBtn">New note</button>
<button id="deleteBtn">Delete note</button>
<input id="titleInput" placeholder="Title">
<textarea id="bodyInput" rows="8" placeholder="Write here..."></textarea>
<p id="saveStatus"></p>
<script src="notes.js"></script>
</body>
</html>
Step 3: Load and save the whole state
// notes.js
const KEY = "notesapp:data";
function loadData() {
try {
const raw = localStorage.getItem(KEY);
if (raw) return JSON.parse(raw);
} catch (error) {
console.error("Corrupt data, starting fresh.", error);
}
return { lastOpened: null, notes: [] };
}
function saveData(data) {
try {
localStorage.setItem(KEY, JSON.stringify(data));
document.getElementById("saveStatus").textContent = "Saved";
} catch (error) {
document.getElementById("saveStatus").textContent = "Save failed";
}
}
let data = loadData();
Step 4: Render the picker and the editor
const picker = document.getElementById("notePicker");
const titleInput = document.getElementById("titleInput");
const bodyInput = document.getElementById("bodyInput");
function currentNote() {
return data.notes.find(n => n.id === data.lastOpened) || null;
}
function render() {
// Fill the dropdown
picker.innerHTML = "";
data.notes.forEach(note => {
const option = document.createElement("option");
option.value = note.id;
option.textContent = note.title || "Untitled";
if (note.id === data.lastOpened) option.selected = true;
picker.appendChild(option);
});
// Fill the editor
const note = currentNote();
titleInput.value = note ? note.title : "";
bodyInput.value = note ? note.body : "";
titleInput.disabled = bodyInput.disabled = !note;
}
picker.addEventListener("change", () => {
data.lastOpened = picker.value;
saveData(data);
render();
});
Step 5: Create, edit, delete — always save after a change
document.getElementById("newBtn").addEventListener("click", () => {
const note = { id: "note-" + Date.now(), title: "", body: "" };
data.notes.push(note);
data.lastOpened = note.id;
saveData(data);
render();
titleInput.focus();
});
document.getElementById("deleteBtn").addEventListener("click", () => {
data.notes = data.notes.filter(n => n.id !== data.lastOpened);
data.lastOpened = data.notes.length ? data.notes[0].id : null;
saveData(data);
render();
});
// Auto-save while typing (a short timer avoids saving every single keypress)
let timer = null;
function autoSave() {
const note = currentNote();
if (!note) return;
note.title = titleInput.value;
note.body = bodyInput.value;
document.getElementById("saveStatus").textContent = "Saving...";
clearTimeout(timer);
timer = setTimeout(() => saveData(data), 400);
}
titleInput.addEventListener("input", autoSave);
bodyInput.addEventListener("input", autoSave);
render();
How the pieces fit together:
- On load,
loadData() reads the single stored object, with a safe fallback if the key is missing or corrupt.
render() always draws the UI from data, never from storage directly — the same single-source-of-truth rule as the to-do example.
- Every mutation (new, delete, switch, edit) ends with
saveData(data), so storage and memory never drift apart.
- The debounced auto-save waits 400 milliseconds after the last keystroke before writing, which keeps typing smooth.
- Refresh, close the browser, reopen tomorrow — the notes are exactly where the user left them.
Extensions to try on your own: a search box that filters notes by title, exporting all notes as a downloaded JSON file, and a "last edited" timestamp shown next to each note.
20. Practice Exercises
- Save your name under the key
"student", then comment out the saving line and reload the page. Print the stored name to the console to confirm persistence.
- Store the number
42, read it back, and predict the output of typeof before running it. Then fix the type with an explicit conversion.
- Build a counter button: each click adds one to a stored count, and the displayed total survives a refresh. Handle the very first visit, when no count exists yet.
- Save an array of three favourite films as JSON. Read it back and print only the second film's name.
- Write a function
remember(key, value) and recall(key, fallback) that wrap localStorage with JSON serialization and null-safe reads, then use them for a language preference.
- Extend the theme example with three themes — light, dark and sepia — stored as a string, and verify the choice survives a browser restart.
- Open two tabs of the same page. In tab A, write a key with a random number every two seconds; in tab B, listen for the
storage event and display the latest value in the page title.
- Implement a "recent items" list that keeps the last five values a user typed into a search box, with no duplicates, using the read–transform–write pattern.
- Create a form with name and email fields that auto-saves both fields separately, restores them on load, and removes both keys when the form is submitted.
- Deliberately store an invalid JSON string (type it by hand in DevTools), then write a reader function with
try...catch that returns a default object instead of crashing.
21. Interview Questions and Answers
What is localStorage and how does it differ from sessionStorage?
Both are parts of the Web Storage API and share the same methods. localStorage keeps data until code or the user deletes it, so it survives browser restarts. sessionStorage keeps data only for the lifetime of the tab; closing the tab wipes it. Both are per-origin and store strings only.
What data types can localStorage store?
Only strings. Keys and values are both stored as text. Numbers and booleans are converted automatically, which causes classic bugs, and objects or arrays must be converted explicitly with JSON.stringify() before saving and JSON.parse() after reading.
What does getItem return when the key does not exist?
It returns null, not an empty string and not an error. Code must check for null before using the value, and a common idiom is JSON.parse(localStorage.getItem(key) || "[]") or a helper with a fallback parameter.
How do you store and retrieve an object in localStorage?
Serialize on the way in and deserialize on the way out: localStorage.setItem("user", JSON.stringify(user)) to save, and const user = JSON.parse(localStorage.getItem("user")) to read. Saving an object directly produces the useless string [object Object].
How does localStorage compare with cookies?
Cookies are small (a few kilobytes) and are automatically sent to the server with every HTTP request, which makes them suitable for server-readable session data. Web storage holds much more data (around 5 MB per origin) and never leaves the browser, which makes it cheaper for purely client-side data but invisible to the server.
What is the storage event and when does it fire?
When one tab changes localStorage, the browser fires a storage event in every other open tab of the same origin. The writing tab itself does not receive it. The event object exposes key, oldValue, newValue and url, and it is commonly used to keep state such as a cart badge in sync across tabs.
How much data can localStorage hold, and what happens when the limit is exceeded?
Browsers allocate roughly 5 MB per origin for web storage. When a write pushes past the quota, setItem throws an exception (a quota-exceeded error), so writes involving user-generated or bulky data should be wrapped in try...catch. Some privacy browsing modes restrict storage further.
Is localStorage secure? Should tokens be stored in it?
No. Any JavaScript running on the page — including third-party scripts — can read everything in localStorage, and nothing is encrypted. It is unsuitable for passwords or sensitive tokens. Sensitive session handling belongs to server-side mechanisms designed for it; localStorage should hold only non-sensitive preferences and data.
How would you persist React state with localStorage?
The pattern is to treat storage as the initial value and save on every change: read the saved value with JSON.parse (with a fallback) to initialise state, and inside the state-update path call localStorage.setItem with JSON.stringify of the new value. In practice this is wrapped once in a small custom hook, often called useLocalStorage, so components just use it like ordinary state that happens to survive reloads.
How do you handle browsers where localStorage is unavailable or blocked?
Accessing or writing localStorage can throw when storage is disabled or restricted, so defensive code wraps the first access in try...catch and falls back to in-memory behaviour. A well-built app degrades gracefully: features work during the session, they simply do not persist.
When would you choose IndexedDB instead of localStorage?
localStorage is a flat key–value store of strings with no querying and a synchronous API, fine for small data. IndexedDB is a full client-side database suited to large volumes of structured data, with indexes and asynchronous operations. Rule of thumb: preferences and small lists go in localStorage; substantial or queryable datasets go in IndexedDB.
How can you delete only your application's keys without clearing other data?
localStorage.clear() removes every key for the origin, including keys written by other scripts, so it is too blunt for routine use. Instead, iterate the stored keys with localStorage.length and localStorage.key(i), collect the ones carrying your app's namespace prefix, and call removeItem on each.
22. Quick Revision Checklist
- I can explain what
localStorage is: persistent, per-origin, string-only browser storage of about 5 MB.
- I know the five methods (
setItem, getItem, removeItem, clear, key) and the length property.
- I know that a missing key reads back as
null and I always supply a fallback.
- I always pair
JSON.stringify on save with JSON.parse on read for objects and arrays.
- I convert stored numbers with
Number() and compare stored booleans with === "true".
- I can state the difference between
localStorage, sessionStorage and cookies, and when each fits.
- I can describe the
storage event and why the writing tab does not hear it.
- I wrap risky writes in
try...catch because exceeding the quota throws.
- I namespace my keys, keep values small, and never store secrets.
- I can build the standard loop: read on load with a default, save on change, remove when done.
23. Official Documentation and Further Reading
localStorage is a plain JavaScript browser API, so the deepest reference material lives in general web platform documentation rather than in framework docs. For this course, the most useful next steps are the resources that connect these foundations to the React work ahead:
Keep practising the read–save–remove loop until it feels automatic; every later framework topic builds directly on it.
Conclusion
localStorage turns a stateless page into an application that remembers its users. The API itself is tiny — five methods and one property — but using it well requires the discipline this page has built step by step: knowing that everything is a string, serializing structures with JSON, reading defensively with fallbacks, handling the quota, namespacing keys, and keeping secrets out.
The deeper takeaway is the pattern, not the API. Read on load, save on change, remove when done — with a single source of truth in memory and storage kept in step with it. That same pattern reappears in React, where state lives in components and effects sync it to storage. Master it here in plain JavaScript, and the React version will feel like a familiar idea wearing new syntax.
Learn more in the React JS Training course, or register for a course demo.