← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 4 of 7

useLocalStorage example

A useLocalStorage composable keeps a ref in sync with the browser's local storage.

In this page:

  1. useLocalStorage example
Syntax
markup
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

markup
<!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
  1. Storing sensitive data
  2. Not handling invalid JSON
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.