Skip to content

Instantly share code, notes, and snippets.

@grocco
Last active September 28, 2025 23:53
Show Gist options
  • Select an option

  • Save grocco/5ba49ffff0db22ac7961b3295969e793 to your computer and use it in GitHub Desktop.

Select an option

Save grocco/5ba49ffff0db22ac7961b3295969e793 to your computer and use it in GitHub Desktop.
Vue@3 useLocalStorage composable
import { onMounted, onUnmounted, ref, watch } from 'vue';
export function useLocalStorage(key: string, defaultValue: any = null, deep = false) {
let initialValue;
try {
initialValue = JSON.parse(localStorage.getItem(key) || "null") || defaultValue
} catch (e) {
initialValue = defaultValue
}
const item = ref(initialValue);
watch(item, (value) => {
if (!value) localStorage.removeItem(key);
else localStorage.setItem(key, JSON.stringify(value))
}, { deep })
const handleStorageChange = (event: StorageEvent) => {
if (event.key === key) {
try {
item.value = JSON.parse(event.newValue || "null")
} catch (e) {
console.log("ERROR parsing local storage value")
item.value = defaultValue
}
}
};
onMounted(() => {
window.addEventListener('storage', handleStorageChange);
});
onUnmounted(() => {
window.removeEventListener('storage', handleStorageChange);
});
return item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment