SoFunction
Updated on 2025-04-04

Vue custom Hook implementation simplifies local storage

introduction

In modern web development, local storage of clients is an important tool for saving and retrieving user data in a browser. This article will explain how to create a powerful and flexible custom Hook using Vue 3's Composition API simplifies thelocalStorageorsessionStorageprocess for managing data.

Background knowledge

Before discussing the specific implementation, let’s review the importance of local storage and why using Vue 3’s Composition API makes it easier to organize your code.

The importance of local storage

In web applications, client local storage is a mechanism for storing data in a browser, which allows us to save information on the user's device. This is very useful for storing user preferences, session status, cache data, etc. By retaining data in local storage, users can still retain some status and information after closing the browser or refreshing the page.

Vue 3's Composition API Advantages

Vue 3 introduces the Composition API, a new way to organize component logic. Compared to previous option APIs, the Composition API provides a more intuitive, flexible and composable code structure. Using the Composition API, we can organize and reuse code blocks more easily, making the code clearer and easier to understand.

Solution Design

Before we dive into the code implementation, let's first look at how local storage works in modern web applications. Given the importance of local storage, we will use Vue 3’s Composition API to create a flexible and easy-to-use custom Hook that simplifies the different storage types (localStorageorsessionStorage) The process of storing and retrieving data.

import { onUnmounted, ref, watch } from 'vue';

/**
  * Custom hook function to use localStorage or sessionStorage
  * @param {string} key - stored key name
  * @param {*} defaultVal - default value
  * @param {string} storage - Storage type, optional value is 'localStorage' or 'sessionStorage'
  * @return {object} - Responsive object, containing value and setValue attributes
  */
export function useLocalStorage(key, defaultVal, storage) {
  const storageType = storage === 'localStorage' ? localStorage : sessionStorage;

  // Create responsive objects using ref  const value = ref(((key)) || defaultVal);

  /**
    * Update the value of the value and store the new value in localStorage or sessionStorage
    * @param {*} newVal - new value
    */
  const setValue = (newVal) => {
    (key, (newVal));
     = newVal;
  };

  /**
    * Listen to the change of value, and instantly store the value of value into localStorage or sessionStorage
    */
  const stopWatch = watch(
    () => (),
    () => {
      (key, ());
    },
    { immediate: true }
  );

  // Use the onUnmounted hook to stop listening to prevent memory leaks  onUnmounted(stopWatch);

  /**
    * Clear the value stored in localStorage or sessionStorage
    */
  const clearValue = () => {
    (key)
     = defaultVal
  }
  
  return {
    value,
    setValue,
  };
}

How to use

Now let's see how to use this custom Hook in Vue component:

<template>
    <el-button type="primary" v-throttle="{ time: 1000, fn: updateStoredValue }">update</el-button>
    <el-button type="primary" v-throttle="{ time: 1000, fn: clearStorage }">clearStorage</el-button>
</template>

<script setup>
  import { useLocalStorage } from 'hooks/'

  //Assignment  const localStorageExample = useLocalStorage(`localStorageExample`, `localStorageExample`, `localStorage`)
  const sessionStorageExample = useLocalStorage(`sessionStorageExample`, `sessionStorageExample`, `sessionStorage`)
  //renew  const updateStoredValue = () => {
    (`11`)
    (`localStorageExampleChanged`)
    (`sessionStorageExampleChanged`)
  }
  //Clear  const clearStorage = () => {
    (`11`)
    ()
    ()
  }
</script>

<style lang="scss" scoped></style>

Practical application scenarios

Imagine that in your Vue project, you need to save your user preferences or user login status. With this custom Hook, you can easily implement these features, making your code clearer and easier to maintain.

Performance considerations

In this custom hook we usewatchTo listen for data changes and use it when component uninstallationonUnmountedStop listening to avoid memory leaks. This design ensures performance and stability.

in conclusion

Through this article, we learned how to use Vue 3’s Composition API to create a powerful custom Hook for simplifying the management of local storage. This Hook provides a clear and flexible solution that makes it easier to use local storage in Vue components.

This is the article about Vue custom Hook simplifying local storage. For more related Vue custom Hook content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!