Local Storage

Persist React state in localStorage with cross-tab sync.

useLocalStorage binds state to a localStorage entry. Values persist across reloads, and changes sync across tabs via the storage event.

import {  } from 'kvantjs/react'
import * as  from 'kvantjs/schema'

export function () {
  const [, ] = (
    'theme',
    .(['light', 'dark']).('light'),
  )

  return (
    < ={() => ( => ( === 'light' ? 'dark' : 'light'))}>
      Theme: {}
    </>
  )
}

Setting a key to undefined removes its entry. Values equal to the schema default are never written. Defaults stay internal. Multiple hooks bound to the same key stay in sync automatically.

Key maps work too:

const [, ] = ({
  : .(['light', 'dark']).('light'),
  : .().(16),
})

( => ({ ..., : . + 1 }))

Session storage

The same API exists for sessionStorage via useSessionStorage. It is scoped to the current tab, cleared when the tab closes, and not shared across tabs:

import {  } from 'kvantjs/react'

const [, ] = ('draft', .().(''))

Options

Prop

Type

Set options once for a component subtree using the options provider:

import {  } from 'kvantjs/react'

< ={{ : { : 'light' } }}>
  {}
</>

On this page