← Back to Snippets
VueJun 2026
useLocalStorage composable
A reactive ref that syncs with localStorage — value persists across page refreshes.
snippet
import { ref, watch } from 'vue'
export function useLocalStorage(key, defaultValue) {
const stored = localStorage.getItem(key)
const value = ref(stored ? JSON.parse(stored) : defaultValue)
watch(value, (newVal) => {
localStorage.setItem(key, JSON.stringify(newVal))
}, { deep: true })
return value
}
// Usage
const theme = useLocalStorage('theme', 'dark')
theme.value = 'light' // persists on next refreshComposablelocalStorageReactivity