Skip to content

useLocalStorageState

State synchronized with localStorage.

State synchronized with localStorage.

Import

import { useLocalStorageState } from '@kamod-ch/hooks'

Live demo

Basic demo

State synchronized with localStorage.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useLocalStorageState } from '@kamod-ch/hooks'

const key = 'kamod-hooks-demo-use-local-storage-state'

export default function UseLocalStorageStateDemo() {
  const [value, setValue] = useLocalStorageState<string>(key, { defaultValue: 'hello' })

  return (
    <div>
      <input value={value} onInput={(event) => setValue(event.currentTarget.value)} />
      <p><strong>Stored value:</strong> {value}</p>
      <div class="demo-actions">
        <button type="button" onClick={() => setValue('reset')}>Set reset</button>
        <button type="button" onClick={() => setValue(undefined)}>Clear</button>
      </div>
    </div>
  )
}

API

TypeScript signature
declare const useLocalStorageState: <T>(key: string, options?: import("../createUseStorageState/index.js").Options<T>) => readonly [T, (this: unknown, value: import("../createUseStorageState/index.js").SetState<T>) => void];
export default useLocalStorageState;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.

Related hooks