State · @vueuse/core v15.0.0 · Reviewed

Persist a Vue value with useLocalStorage

A ref that saves itself in the browser, so the value is still there after a page reload.

App.vueVue SFCOpen in Vue Playground ↗
Live preview

Edit the code and the preview updates as you type.

What it does

A normal ref resets every time the page reloads. useLocalStorage gives you a ref backed by the browser's localStorage: change the value and it's saved, reload and it comes back.

It also does the boring parts. localStorage can only store text, so it turns numbers, booleans and objects into text and back for you. It saves deep changes like cart.value.push(item), and it keeps open tabs in sync: change the value in one tab and the others update.

The code

Vue · Composition API
import { useLocalStorage } from '@vueuse/core'

// 'cart' is the storage key, [] the starting value
const cart = useLocalStorage('cart', [])

cart.value.push({ id: 42, qty: 1 }) // saved automatically

Where you'd use it

  • A guest shopping cart that survives a refresh
  • "Don't show this again" on banners and tips
  • Saving a long form as a draft while someone types
  • Remembering choices like grid or list view, sort order and filters
  • A "recently viewed products" list

Real-world example: a guest shopping cart

A guest expects a cart to survive a refresh. A normal ref() resets on reload, while useLocalStorage keeps a small client-side cart between visits. It is a convenience cache: after sign-in, sync the cart with your server so it follows the customer across devices.

import { useLocalStorage } from '@vueuse/core'

const cart = useLocalStorage('guest-cart', [])
function addToCart(product) {
  const line = cart.value.find(item => item.id === product.id)
  if (line) line.qty++
  else cart.value.push({ id: product.id, name: product.name, qty: 1 })
}

Choose storage for the job

StorageGood fitTrade-off
ref()Temporary component stateLost on reload
sessionStorageState for one tab sessionCleared when the session ends
localStorageSmall preferences and guest cart cacheClient-only, string-backed, same-origin
useCookie()Small values the Nuxt server must readSent with requests; keep values small
IndexedDBLarger structured data and offline cachesAsync API with more setup
BackendAccount data and cross-device stateRequires network and server-side persistence

Nuxt hydration: matching the first render

The server cannot read the browser's localStorage. If a saved theme or cart changes markup, the server output may differ from the first client render. With initOnMounted: true, the initial value is rendered first and storage is read after mount:

// Server render: 'grid'
// First browser render: 'grid'
// After mount: saved value, e.g. 'list'
const view = useLocalStorage('view', 'grid', { initOnMounted: true })

Use useCookie instead when the server must render the saved value on the first response. For existing object data, mergeDefaults: true can merge new defaults, but treat schema changes deliberately and migrate stored values when needed.

Other small browser preferences fit the same pattern: useLocalStorage('theme', 'light') for a theme, useLocalStorage('product-view', 'grid') for a layout choice, or a bounded array for recently viewed product ids. For a dismissible promotion, store a boolean or expiry time so it can return when the campaign changes.

Production mistakes

  • Do not store authentication credentials here; JavaScript on the page can read them. Use appropriately configured HttpOnly cookies.
  • Storage can be unavailable or throw in restricted browser contexts. Handle failures if persistence is essential.
  • It is not a database or cross-device sync. Persist important business data on the server.
  • Changes in another tab can overwrite local values; define how your app handles cross-tab updates and conflicts.

Performance

Web Storage reads and writes are synchronous. Keep saved values small and avoid writing large objects on every keystroke; debounce draft persistence or move larger/offline data to IndexedDB.

In Nuxt (and other gotchas)

Expect a hydration mismatch. The server has no localStorage, so it renders the starting value. The browser then reads the saved value and renders something different. Vue warns about the mismatch, and the user sees a flash.

Fix it with initOnMounted: true. The ref keeps its starting value until the component mounts, so the server render and the first browser render match, and then it loads the saved value:

const view = useLocalStorage('view', 'grid', { initOnMounted: true })

If the server needs the value to render the right HTML (currency, language, theme), use Nuxt's useCookie instead. Cookies are sent with every request, so the server can read them.

Two smaller traps. Choose a sensible initial value and serializer for the data shape you expect. And if you later add a new field to a stored object, people who already have the old object won't get the new field unless you pass mergeDefaults: true.

When not to use it

Never store tokens or personal data. Any script on the page, including a compromised third-party one, can read localStorage. Keep auth in httpOnly cookies.

It isn't a database. You get about 5 MB, and every read and write blocks the page. For large data, use IndexedDB, for example useIDBKeyval from @vueuse/integrations. Data that should follow the user to another device belongs on your server.

Links

Need a hand with your Vue or Nuxt app?

Related functions