useLocalStorage example
A useLocalStorage composable keeps a ref in sync with the browser's local storage.
In this page:
Syntax
import { ref, watch } from 'vue';
export function useLocalStorage(key, initial) {
const value = ref(JSON.parse(localStorage.getItem(key)) ?? initial);
watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true });
return value;
}
useLocalStorage example
The composable reads the stored JSON as the initial value and uses watch to write every change back. Because it returns a ref, components use it exactly like normal state and it survives page reloads.
Always guard JSON parsing and remember storage only holds strings.
Note:
Storage is synchronous and limited in size, so keep values small.
Example: useLocalStorage example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<input v-model="name">
<p>Hello, {{ name }}! (value is saved in localStorage)</p>
</div>
<script>
function useLocalStorage(key, initial) {
let start = initial;
try { const raw = localStorage.getItem(key); if (raw !== null) start = JSON.parse(raw); } catch (e) {}
const value = Vue.ref(start);
Vue.watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true });
return value;
}
Vue.createApp({
setup() {
const name = useLocalStorage("username", "Ada");
return { name };
},
}).mount("#app");
const i = document.querySelector("input");
i.value = "Grace"; i.dispatchEvent(new window.Event("input"));
setTimeout(() => console.log("saved in storage:", localStorage.getItem("username")), 50);
</script>
</body>
</html>
<!-- Output:
Rendered: Hello, Grace! (value is saved in localStorage)
console: saved in storage: "Grace"
-->
Live Example
Related Topics
Common Mistakes
- Storing sensitive data
- Not handling invalid JSON
- Forgetting deep: true for objects
Chapter Summary
- Read initial value from storage
- watch writes changes back
- Returns a normal ref
- Guard JSON parsing
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: