JAVASCRIPT
Vue 3 Composable for Persisting State to Local Storage
Learn to create a custom Vue 3 composable to effortlessly persist reactive state to local storage, ensuring data persistence across page reloads and enhancing user experience.
import { ref, watch, onMounted } from 'vue';
export function useLocalStorage(key, initialValue) {
const storedValue = localStorage.getItem(key);
const value = ref(storedValue ? JSON.parse(storedValue) : initialValue);
watch(value, (newValue) => {
localStorage.setItem(key, JSON.stringify(newValue));
}, { deep: true }); // Deep watch for objects/arrays
onMounted(() => {
// Optional: Listen for changes from other tabs/windows
const handleStorageChange = (event) => {
if (event.key === key && event.newValue !== null) {
value.value = JSON.parse(event.newValue);
}
};
window.addEventListener('storage', handleStorageChange);
// onUnmounted(() => window.removeEventListener('storage', handleStorageChange)); // Add cleanup if needed
});
return value;
}
// How to use in a component:
// <template>
// <div>
// <input type="text" v-model="userName" placeholder="Enter your name">
// <p>Hello, {{ userName }}!</p>
// <button @click="count++">Count: {{ count }}</button>
// </div>
// </template>
// <script setup>
// import { useLocalStorage } from './composables/useLocalStorage';
// const userName = useLocalStorage('user-name', 'Guest');
// const count = useLocalStorage('counter', 0);
// </script>
How it works: This composable `useLocalStorage` simplifies persisting reactive state to the browser's local storage. It takes a key and an initial value, returning a reactive `ref`. Any changes to this ref are automatically saved to local storage via a `watch` effect. On component mount, it also initializes the ref from storage if data exists, and includes a basic listener for cross-tab storage updates, enhancing data consistency.