npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-url-state-hook

v0.1.1

Published

Tiny, dependency-free React hook to sync component state with URL search params and query strings

Downloads

14

Readme

React URL State Hook – Sync React State with Query Parameters

Tiny, dependency-free React hook for synchronizing component state with URL search params and query strings.

Keep filters, pagination, and shareable URLs in sync across React Router, Next.js, Remix, and any custom router without adding heavyweight dependencies.

npm version bundle size license

Use Cases

  • Persist search filters and sort order between refreshes or page changes
  • Generate shareable URLs for dashboards and internal tooling
  • Replace useSearchParams with a more ergonomic API that handles nested objects
  • Keep query string state aligned across tabs, back button navigation, and SSR

Features

  • Tiny: <1 KB gzipped
  • Zero dependencies: No external runtime dependencies
  • SSR-safe: Works with server-side rendering
  • Type-coercion: Automatically parses numbers and booleans
  • Nested objects & arrays: Full support with dot notation
  • Debouncing: Built-in debounce support
  • History modes: Push or replace state
  • Hash routing: Optional hash-based routing
  • Tree-shakeable: ESM-first with CJS fallback

Installation

npm install react-url-state-hook

Usage

Basic Example

import { useUrlState } from 'react-url-state-hook'

function SearchPage() {
  const [filters, setFilters] = useUrlState({
    query: '',
    page: 1,
    sort: 'asc'
  })

  return (
    <div>
      <input
        value={filters.query}
        onChange={(e) => setFilters({ query: e.target.value })}
      />
      <button onClick={() => setFilters({ page: filters.page + 1 })}>
        Next Page
      </button>
      <span>Current page: {filters.page}</span>
    </div>
  )
}

The URL automatically syncs: /?query=react&page=2&sort=asc

Next.js App Router Example

'use client'
import { usePathname } from 'next/navigation'
import { useUrlState } from 'react-url-state-hook'

export default function ProductsPage() {
  const pathname = usePathname()
  const [filters, setFilters] = useUrlState(
    { q: '', category: 'all' },
    {
      basePath: pathname,
      history: 'replace'
    }
  )

  return (
    <section>
      <input
        value={filters.q}
        placeholder="Search products"
        onChange={(event) => setFilters({ q: event.target.value })}
      />
      <select
        value={filters.category}
        onChange={(event) => setFilters({ category: event.target.value })}
      >
        <option value="all">All</option>
        <option value="new">New</option>
        <option value="sale">On Sale</option>
      </select>
    </section>
  )
}

Passing basePath from usePathname() keeps the hook aligned with the page segment while still letting the URL query string stay in sync.

Nested Objects & Arrays

const [state, setState] = useUrlState({
  user: { name: '', age: 0 },
  tags: []
})

setState({
  user: { name: 'Alice', age: 30 },
  tags: ['react', 'hooks']
})
// URL: /?user.name=Alice&user.age=30&tags=react&tags=hooks

Strip Default Values

Omit keys that match the initial state:

const [state, setState] = useUrlState(
  { page: 1, sort: 'asc' },
  { stripDefaults: true }
)

setState({ page: 1, sort: 'desc' })
// URL: /?sort=desc (page=1 is omitted)

Push vs Replace History

// Replace mode (default): doesn't add history entries
const [state, setState] = useUrlState({ page: 1 })

// Push mode: adds history entries (back button works)
const [state, setState] = useUrlState(
  { page: 1 },
  { history: 'push' }
)

Debounce URL Updates

Useful for search inputs to avoid URL thrashing:

const [filters, setFilters] = useUrlState(
  { search: '' },
  { debounceMs: 300 }
)

// URL updates 300ms after the last setState call

Hash Routing

For hash-based routing (e.g., #/page?query=foo):

const [state, setState] = useUrlState(
  { query: '' },
  { routing: 'hash' }
)

API Methods

The hook returns a triple: [state, setState, api]

const [state, setState, api] = useUrlState({ page: 1, sort: 'asc' })

// Merge state (like setState)
setState({ page: 2 })

// Replace entire state
api.replace({ page: 3, sort: 'desc' })

// Reset to initial state
api.reset()

// Clear all managed params from URL
api.clear()

// Set a single key
api.setKey('page', 5)

// Get current search string
const search = api.getSearch() // "page=5&sort=asc"

Initial Sync Strategy

Control how URL and state merge on mount:

// URL wins (default): URL params override initialState
const [state] = useUrlState(
  { page: 1 },
  { syncOnInit: 'url-wins' }
)
// URL: /?page=5 → state.page = 5

// State wins: initialState overrides URL
const [state] = useUrlState(
  { page: 1 },
  { syncOnInit: 'state-wins' }
)
// URL: /?page=5 → state.page = 1

Transform Functions

Apply custom serialization/deserialization per key:

const [state, setState] = useUrlState(
  { date: new Date() },
  {
    transform: {
      date: {
        in: (val) => new Date(val),      // Parse from URL
        out: (val) => val.toISOString()  // Serialize to URL
      }
    }
  }
)

SSR (Server-Side Rendering)

The hook safely returns initial state on the server:

// On server (window is undefined)
const [state, setState, api] = useUrlState({ page: 1 })
// Returns: [{ page: 1 }, noop, apiNoop]

Options

All options are optional:

| Option | Type | Default | Description | |--------|------|---------|-------------| | history | 'push' \| 'replace' | 'replace' | History API mode | | routing | 'browser' \| 'hash' | 'browser' | Routing mode | | debounceMs | number | 0 | Debounce delay for URL updates | | stripDefaults | boolean | false | Omit keys equal to initialState | | syncOnInit | 'url-wins' \| 'state-wins' | 'url-wins' | Initial sync strategy | | serialize | (obj) => string | built-in | Custom serializer | | parse | (qs) => object | built-in | Custom parser | | transform | object | {} | Per-key transform functions | | basePath | string | '' | Base path for browser routing |

Browser Support

Requires the History API (all modern browsers). For legacy browsers, consider polyfills.

Size

  • ESM: ~2.5 KB minified, ~800 bytes gzipped
  • CJS: ~2.6 KB minified, ~850 bytes gzipped

How It Works

  1. On mount, parses the current URL and merges with initialState
  2. On state changes, serializes managed keys and updates the URL
  3. Listens to popstate events to sync state on back/forward navigation
  4. Preserves unmanaged query params (e.g., UTM parameters)
  5. SSR-safe: no-ops when window is undefined

Works With

  • Plain React apps and legacy codebases
  • React Router v6+ (routes, loaders, search params)
  • Next.js (Pages Router or App Router client components)
  • Remix and other server frameworks with universal routing
  • Any routing library (doesn't rely on routing APIs)

FAQ

How is this different from useSearchParams or nuqs?
useUrlState manages nested objects, arrays, debounce, and history modes out of the box, making it easier to persist complex UI state without manually parsing strings.

Does it work without React Router?
Yes. The hook only depends on the browser History API, so it works in vanilla React apps, single-file embeds, and custom routers.

License

MIT

Contributing

Issues and PRs welcome! Please ensure tests pass before submitting.


Made by Lalit Patil