one-hook
Size
0.75 kb
View source

useStorage

A simple typesafe state manager using localStorage or sessionStorage.

Features

  • Built-in Validation: Validate with zod, valibot, arktype or with a simple function.
  • Tab Sync: The state is synced across multiple browser tabs when using the localStorage.
  • Component Sync: The state is synced across all components.

Installation

npm install @1hook/use-storage

Quick Start

Setup the State

Use defineCookie to configure validation rules and the type of storage.

sidebar-width.ts
import {  } from 'zod'
import {  } from '@1hook/use-storage'

export const [] = ({
  : 'sidebar-width',
  : .().(200),
  : 'local',
})

Read and Write.

Changes to the state are synchronized across all instances of the hook and across browser tabs.

layout.tsx
function () {
  const [, ] = ()

  return (
    <>
      <Sidebar ={} ={} />
      <>...</>
    </>
  )
}

Storage updates are automatically synchronized across all instances of the hook and across browser tabs.

Validation

To ensure data integrity, the storage should be validated.

👉 Functional validation

For simple cases you can use a function to validate the storage.

({
  : 'search',
  : () => ( ?? ''),
  : 'local',
})

👉 Schema validation

For more complex cases you can use a schema to validate the storage. Compatible validation libraries include zod 3.24+, valibot 1.0+ or arktype 2.0+. Check out Standard Schema for more info.

import {  } from 'zod'

({
  : 'search',
  : .().(''),
  : 'local',
})

Outside of React

defineStorage returns a standalone utility object that provides methods to get, set or clear the value outside of React components.

export const [, ] = ({
  : 'my-storage',
  : .().(),
  : 'local',
})

Using it still triggers a React re-render.

import {  } from './storage'

// Write
.('new-value')

// Read
.()

// Clear
.()

API Reference

👉 defineStorage

function defineStorage(options?: DefineStorageOptions): [useStorage, Storage]

DefineStorageOptions

The options of the storage service.

PropTypeDefault
deserialize?
((value: string) => any)
-
serialize?
((value: unknown) => string)
-
validate
TValidator
-
key
string
-
type
"local" | "session"
-

👉 useStorage

Manage storage state like with useState.

function useStorage(): [state, setState]

👉 Storage

Read and write to the storage outside of React.

On this page