How to use Vue with localStorage
Persisting application state across browser sessions improves user experience by maintaining preferences, form data, and application state. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented localStorage integration in Vue applications throughout my 11 years of framework development. The most practical approach is combining Vue’s reactivity with localStorage, using watchers to automatically save state changes. This method provides seamless data persistence without manual save operations.
Use watchers to automatically sync Vue state with localStorage.
import { ref, watch, onMounted } from 'vue'
export default {
setup() {
const userPreferences = ref({
theme: 'light',
language: 'en'
})
onMounted(() => {
const saved = localStorage.getItem('userPreferences')
if (saved) {
userPreferences.value = JSON.parse(saved)
}
})
watch(userPreferences, (newValue) => {
localStorage.setItem('userPreferences', JSON.stringify(newValue))
}, { deep: true })
return { userPreferences }
}
}
Here the component loads saved preferences from localStorage when mounted, parsing the JSON string back into an object. A deep watcher monitors the preferences object and automatically saves any changes to localStorage as JSON. The deep: true option ensures nested property changes trigger the watcher.
Best Practice Note:
This is the pattern we use in CoreUI Vue components for persisting user settings and theme preferences. Always handle JSON parse errors with try-catch blocks, use a composable for reusable localStorage logic, and consider storage quotas when saving large amounts of data.



