Router Query

Bind React state to the Next.js pages router query.

useRouterQuery binds state to router.query, navigating through the Next.js pages router. The URL is the single source of truth: refreshing, sharing, or bookmarking the link restores the exact state. Writes are shallow by default, so data fetching methods don't re-run, and the URL hash is preserved.

import {  } from 'kvantjs/next/pages'
import * as  from 'kvantjs/schema'

function () {
  const [, ] = ('q', .().(''))

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

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 [, ] = ({
  : .().(''),
  : .().(0),
  : .(['asc', 'desc']).('asc'),
  : .(.()).([]), // repeated params: ?tags=a&tags=b
})

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

Fast-changing values

kvant does not yet provide built-in throttle/debounce for URL writes. Until then, avoid binding state directly to quickly changing values (text inputs, sliders), or wrap the binding in a throttled layer with local state:

import { useThrottleFn } from 'react-use'

function SearchInput() {
  const [search, setSearch] = useRouterQuery('q', kv.string().default(''))

  // Local state updates instantly; the URL follows at most every 300 ms
  const [text, setText] = useState(search)
  useThrottleFn(setSearch, 300, [text])

  return <input value={text} onChange={e => setText(e.target.value)} />
}

Options

Prop

Type

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

import {  } from 'kvantjs/next/pages'

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

On this page