JAVASCRIPT

Persisting Reactive State with `useLocalStorage` Composable

Learn to create a Vue 3 Composition API composable for easily persisting and retrieving reactive state to and from browser local storage, enhancing data persistence.

// 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;
}

// App.vue (or any component)
// <template>
//   <input type="text" v-model="userName" placeholder="Enter your name" />
//   <p>Hello, {{ userName }}!</p>
//   <label>
//     <input type="checkbox" v-model="darkMode" /> Dark Mode
//   </label>
// </template>
//
// <script setup>
// import { useLocalStorage } from './composables/useLocalStorage';
//
// const userName = useLocalStorage('user-name', 'Guest');
// const darkMode = useLocalStorage('dark-mode', false);
//
// // Example for a more complex object
// const userSettings = useLocalStorage('user-settings', { notifications: true, theme: 'light' });
//
// function toggleNotifications() {
//   userSettings.value.notifications = !userSettings.value.notifications;
// }
// </script>
How it works: This composable provides a reactive reference that automatically syncs its value with the browser's local storage. When the `value` ref changes, a `watch` effect triggers an update to `localStorage`. Upon initialization, it attempts to load the value from `localStorage` or falls back to a provided `defaultValue`. This pattern significantly simplifies the process of persisting small, reactive pieces of application state across page reloads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs