Making Your SPA Remember State with localStorage — 3 Patterns and Their Pitfalls
Making Your SPA Remember State with localStorage — 3 Patterns and Their Pitfalls In a vanilla JavaScript SPA without build tools, you want the page to return to "where you were" after a reload. Rea...

Source: DEV Community
Making Your SPA Remember State with localStorage — 3 Patterns and Their Pitfalls In a vanilla JavaScript SPA without build tools, you want the page to return to "where you were" after a reload. React has zustand + persist, Vue has pinia-plugin-persistedstate, but without a framework you're writing raw localStorage calls. Running a home lab dashboard (single-file SPA, ~3000 lines), I use localStorage for three distinct purposes. Here are the patterns and the pitfalls I only discovered after implementing them. Pattern 1: Persisting View State The most common SPA annoyance — pressing F5 dumps you back to the home page. function showView(viewName) { document.querySelectorAll(".view").forEach(v => v.classList.remove("active")); document.getElementById(viewName + "View").classList.add("active"); // Save the current view localStorage.setItem('dashboardCurrentView', viewName); } document.addEventListener("DOMContentLoaded", function() { const savedView = localStorage.getItem('dashboardCurre