Skip to content
D
Documentation

Sync state with the URL

how-to
4 min readUpdated

Use URL-backed storage when you want someone opening a link to see the same store data. The examples below restore state when the store initializes and write subsequent edits to a hash or query parameter.

Start in the client-rendered project from the React quick start. It already installs Zustand; no additional package is needed. In another React project, install it with:

bash
npm install zustand

create binds the store to a React hook. Wrap its initializer with persist, then pass a custom StateStorage through createJSONStorage. Your adapter transports strings; the helper handles JSON serialization and deserialization.

Connect state with URL hash

The hash adapter stores the fish count under food-storage in the fragment. Clicking Add a fish changes the count and the address bar; opening that address in another tab restores the count.

  1. Add the adapter and store. Read the fragment as URL parameters so writes preserve other fragment keys. Return null when the store key is missing.
ts
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import type { StateStorage } from 'zustand/middleware'

const hashStorage: StateStorage = {
  getItem: (key) => {
    const params = new URLSearchParams(window.location.hash.slice(1))
    return params.get(key)
  },
  setItem: (key, value) => {
    const params = new URLSearchParams(window.location.hash.slice(1))
    params.set(key, value)
    window.location.hash = params.toString()
  },
  removeItem: (key) => {
    const params = new URLSearchParams(window.location.hash.slice(1))
    params.delete(key)
    window.location.hash = params.toString()
  },
}

type FishStore = {
  fishes: number
  addAFish: () => void
}

export const useFishStore = create<FishStore>()(
  persist(
    (set, get) => ({
      fishes: 0,
      addAFish: () => set({ fishes: get().fishes + 1 }),
    }),
    {
      name: 'food-storage',
      storage: createJSONStorage(() => hashStorage),
      partialize: (state) => ({ fishes: state.fishes }),
    },
  ),
)

The hash adapter puts the helper's serialized string directly into a URL parameter; see Persist store state for the envelope format and selecting saved fields.

  1. Add a component that consumes the store hook.
tsx
import { useFishStore } from './hash-store'

export default function HashCounter() {
  const fishes = useFishStore((state) => state.fishes)
  const addAFish = useFishStore((state) => state.addAFish)

  return (
    <main style={{ minHeight: 400 }}>
      <h1>Fish in the URL hash</h1>
      <p aria-live="polite">Fishes: {fishes}</p>
      <button type="button" onClick={addAFish}>Add a fish</button>
      <p>After adding a fish, copy the address to share this count.</p>
    </main>
  )
}
  1. Mount HashCounter from ./HashCounter.tsx in place of the counter, following the React quick start's mounting and run steps.

With no saved fragment, the mounted component displays Fishes: 0. Each click increments the rendered count and writes the fragment. Reloading reads the envelope once through the storage helper during initialization; no manual rehydration call is needed.

Compare this with the authors' live hash demo.

Persist and connect state with query parameters

Use a query adapter when you also want a local copy. This example reads the store's query parameter first and falls back to localStorage when that key is absent. It always writes the local copy, but updates the query only when the address already has query parameters.

  1. Add a separate store. The adapter uses history.replaceState to update the URL in place, preserving the path, fragment, unrelated parameters, and existing history state.
ts
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import type { StateStorage } from 'zustand/middleware'

const storageName = 'fishAndBearsStore'

const persistentStorage: StateStorage = {
  getItem: (key) => {
    const params = new URLSearchParams(window.location.search)
    return params.get(key) ?? window.localStorage.getItem(key)
  },
  setItem: (key, value) => {
    if (window.location.search) {
      const url = new URL(window.location.href)
      url.searchParams.set(key, value)
      window.history.replaceState(window.history.state, '', url)
    }
    window.localStorage.setItem(key, value)
  },
  removeItem: (key) => {
    const url = new URL(window.location.href)
    url.searchParams.delete(key)
    window.history.replaceState(window.history.state, '', url)
    window.localStorage.removeItem(key)
  },
}

type LocalAndUrlStore = {
  typesOfFish: string[]
  addTypeOfFish: (fishType: string) => void
  numberOfBears: number
  setNumberOfBears: (numberOfBears: number) => void
}

type ShareableState = Pick<LocalAndUrlStore, 'typesOfFish' | 'numberOfBears'>

export const useLocalAndUrlStore = create<LocalAndUrlStore>()(
  persist(
    (set) => ({
      typesOfFish: [],
      addTypeOfFish: (fishType) =>
        set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),
      numberOfBears: 0,
      setNumberOfBears: (numberOfBears) => set({ numberOfBears }),
    }),
    {
      name: storageName,
      storage: createJSONStorage(() => persistentStorage),
      partialize: (state) => ({
        typesOfFish: state.typesOfFish,
        numberOfBears: state.numberOfBears,
      }),
    },
  ),
)

export function buildShareableUrl(state: ShareableState): string {
  const url = new URL(window.location.href)
  url.searchParams.set(storageName, JSON.stringify({ state, version: 0 }))
  return url.toString()
}

The generated link uses the same key and versioned envelope as the adapter. buildShareableUrl returns an absolute URL without navigating or replacing current edits. Version 0 matches persist's default version.

  1. Add a component that edits both fields and renders a shareable link from the current store values.
tsx
import { buildShareableUrl, useLocalAndUrlStore } from './query-store'

export default function QueryState() {
  const typesOfFish = useLocalAndUrlStore((state) => state.typesOfFish)
  const numberOfBears = useLocalAndUrlStore((state) => state.numberOfBears)
  const addTypeOfFish = useLocalAndUrlStore((state) => state.addTypeOfFish)
  const setNumberOfBears = useLocalAndUrlStore((state) => state.setNumberOfBears)
  const shareUrl = buildShareableUrl({ typesOfFish, numberOfBears })

  return (
    <main style={{ minHeight: 400 }}>
      <h1>Fish and bears in query parameters</h1>
      <p aria-live="polite">Fish: {typesOfFish.join(', ') || 'None'}</p>
      <button type="button" onClick={() => addTypeOfFish('salmon')}>
        Add salmon
      </button>
      <p aria-live="polite">Bears: {numberOfBears}</p>
      <button type="button" onClick={() => setNumberOfBears(numberOfBears + 1)}>
        Add a bear
      </button>
      <p><a href={shareUrl} target="_blank" rel="noreferrer">Open shared state in a new tab</a></p>
    </main>
  )
}
  1. Change the component import and rendered element in src/main.tsx to QueryState from ./QueryState.tsx, keeping the entry file's other wiring. Build and run as above.

Without saved data, the component displays Fish: None and Bears: 0. Add salmon and a bear, then open the shared-state link: the new tab displays those values. The original tab retains its edits. With no query string, edits save locally and the address stays unchanged; the link still contains the current data. In the shared tab, further edits also update the query without a page reload.

To always populate the query, remove the if (window.location.search) condition around the URL write in setItem. See the authors' live query demo for conditional URL persistence alongside local storage.

Options that matter

OptionTypeDefaultWhat it does
namestringRequiredNames the storage item and, in these adapters, the URL parameter. Use a unique name per store.
storagePersistStorage<PersistedState>createJSONStorage(() => window.localStorage)Selects the storage engine. These examples supply URL-backed adapters.
partialize(state: S) => PersistedStateIdentity functionPicks the data fields to write, leaving actions out of the envelope.
versionnumber0Identifies the stored schema. A different stored version is not used without a migration.

createJSONStorage adapts your string-based storage to PersistStorage. For schema changes, update both the store's version and the share-link envelope; see Migrate persisted data.

Pitfalls

  • These adapters run in the browser. For server-rendered React, use the setup in Server-render React stores.
  • Treat the fragment as encoded key/value data, not a heading anchor. Both adapters preserve unrelated parameter keys, but the hash adapter owns the fragment's format.
  • Keep the string boundary intact: getItem returns the stored string or null, and setItem receives an already serialized envelope. Let the helper parse it once.
  • createJSONStorage does not validate the deserialized state. For production links, validate untrusted data with a custom PersistStorage, as described in Implement custom storage. A version number identifies a schema; it is not an integrity check. Parse errors reach onRehydrateStorage's completion callback; see Control state hydration for error reporting.
  • These adapters do not subscribe to browser navigation events. They load at initialization, then persist store edits. Opening a shared link in a separate tab avoids replacing work in the current store; do not add automatic rehydration on every URL change.

Was this page helpful?

Sync state with the URL — zustand · GPT-6.1 Sol