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
Maintainers
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.
Use Cases
- Persist search filters and sort order between refreshes or page changes
- Generate shareable URLs for dashboards and internal tooling
- Replace
useSearchParamswith 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-hookUsage
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=hooksStrip 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 callHash 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 = 1Transform 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
- On mount, parses the current URL and merges with
initialState - On state changes, serializes managed keys and updates the URL
- Listens to
popstateevents to sync state on back/forward navigation - Preserves unmanaged query params (e.g., UTM parameters)
- SSR-safe: no-ops when
windowis 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
