Advanced Usage

Building your own bindings with useKvantState and defineKvantState.

Adapters

Under the hood, every kvant binding talks to an adapter: a small factory that connects a key-value interface (URL, cookies, local storage, etc.) to the state layer.

type KvantAdapter<T, Options> = (
  keys: string[],
  options: Partial<Options>,
) => KvantAdapterInterface<T>

To learn more about the adapter contract and how to implement your own, see Custom Adapters.

useKvantState

The framework-idiomatic bindings (useLocalStorage, useCookies, etc.) are pre-bound versions of the generic useKvantState, which takes an adapter explicitly:

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

const [, ] = (
  ,
  'consent',
  .().(false),
  { : 60 * 60 * 24 * 365, : 'lax' },
)

Signatures:

// Single key
const [state, setState] = useKvantState(adapter, key, schema, options)

// Key map: bind several keys in one call
const [state, setState] = useKvantState(adapter, keyMap, options)

defineKvantState

While useKvantState passes the adapter at every call site, defineKvantState pre-binds an adapter once and returns a ready-to-use hook plus an options provider:

import {  } from 'kvantjs/react'
import {  } from 'kvantjs'

export const {
  : ,
  : ,
} = ()

As an alternative to options providers, you can also specify default adapter options for the entire binding:

import {  } from 'kvantjs/react'
import {  } from 'kvantjs'

export const {
  : ,
  : ,
} = (, {
  : 60 * 60 * 24 * 365,
  : 'lax'
})

This is exactly how the pre-bound hooks are built internally, and the recommended way to pre-configure an adapter for your whole app.

On this page