JAVASCRIPT

Create a Reactive useLocalStorage Composable in Vue 3

Build a Vue 3 composable (`useLocalStorage`) to effortlessly synchronize reactive state with browser local storage, perfect for persisting user preferences.

// composables/useLocalStorage.js
import { ref, watch } from 'vue';

export function useLocalStorage(key, defaultValue) {
  const storedValue = localStorage.getItem(key);
  const value = ref(storedValue ? JSON.parse(storedValue) : defaultValue);

  watch(value, (newValue) => {
    localStorage.setItem(key, JSON.stringify(newValue));
  }, { deep: true });

  return value;
}

// In your component:
/*
<template>
  <div>
    <p>Your name: {{ name }}</p>
    <input v-model="name" type="text" placeholder="Enter your name" />
    <p>Counter: {{ counter }}</p>
    <button @click="counter++">Increment</button>
  </div>
</template>

<script setup>
import { useLocalStorage } from '@/composables/useLocalStorage'; // Adjust path

const name = useLocalStorage('user-name', 'Guest');
const counter = useLocalStorage('app-counter', 0);
</script>
*/
How it works: This `useLocalStorage` composable in Vue 3 provides a reactive way to interact with the browser's local storage. It initializes a `ref` with a value retrieved from local storage or a provided default. A `watch` effect then continuously synchronizes any changes to this `ref` back to local storage, ensuring that the state persists across browser sessions. It automatically handles JSON parsing and stringification for complex data types.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs