Web storage
| localStorage set | |
| Read with fallback | |
| Store objects | |
| sessionStorage |
localStorage set
localStorage keeps strings after the tab closes. setItem stores under a key, and getItem reads it back on the next visit. Both calls are synchronous, so keep stored values small:
localStorage.setItem("theme", "dark");
Reload the page and the pair is still there. Keys are plain strings, so prefix them with the app name to avoid collisions.
Read with fallback
getItem returns a string or null when the key was never stored. Provide a fallback with double question marks, so the rest of the code always sees a real string:
const theme: string = localStorage.getItem("theme") ?? "light";
The first visit reads light, later visits read the saved choice. One line, no if needed, and no null leaks further.
Store objects
Storage holds strings only, so stringify objects on the way in and parse them on the way out. Wrap both directions in helpers that fall back to defaults when the stored text is missing:
interface Prefs { theme: string; size: number; }
function savePrefs(prefs: Prefs): void {
localStorage.setItem("prefs", JSON.stringify(prefs));
}
function loadPrefs(): Prefs {
const raw = localStorage.getItem("prefs");
if (raw === null) {
return { theme: "light", size: 14 };
}
return JSON.parse(raw) as Prefs;
}
The interface keeps the parsed value honest, and the early return covers fresh visitors. Every caller of loadPrefs receives complete prefs, never a hole.
sessionStorage
sessionStorage shares the same methods but a different lifetime: values vanish when the tab closes. Use it for per-tab state like a draft or a wizard step that must not leak into other tabs:
sessionStorage.setItem("draft", "hello");
const draft: string = sessionStorage.getItem("draft") ?? "";
Same calls, tab-sized memory. Long-lived choices go to localStorage, temporary tab state goes here.
Next: npm packages
Article author: Arthur Isaev