Skip to content

Latest commit

 

History

History
105 lines (76 loc) · 2.13 KB

README.md

File metadata and controls

105 lines (76 loc) · 2.13 KB

use-query-sync

A React hook that synchronizes state with URL query parameters. It's useful when you want to make your app's state shareable and bookmarkable via URLs.

It works with Next.js and React.

Why

URLs should reflect application state. When users share URLs, the recipient should see exactly what the sender saw. Most React apps don't do this well - they maintain state in memory but not in the URL. This hook solves that problem.

Usage

import { useUrlState } from "use-query-sync";

// With primitive values
const [searchTerm, setSearchTerm] = useUrlState("", { name: "search" });

// With objects
const [filters, setFilters] = useUrlState({
	category: "all",
	sort: "desc",
});

The hook automatically:

  • Serializes state changes to URL query parameters
  • Deserializes URL parameters back to state when the URL changes
  • Handles browser navigation (back/forward) correctly
  • Works with both primitive values and objects

Installation

npm install use-query-sync

API

const [state, setState] = useUrlState(initialState, options?)

Parameters

  • initialState: The initial state value (any serializable value)
  • options: Optional configuration object
    • name: Query parameter name (defaults to 'q')
    • initFromQuery: Whether to initialize from URL (defaults to true)

Returns

  • state: Current state value
  • setState: Function to update state and URL

Examples

Search Input

function SearchBar() {
	const [query, setQuery] = useUrlState("", { name: "search" });

	return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}

Filter Controls

function Filters() {
	const [filters, setFilters] = useUrlState({
		category: "all",
		sortBy: "date",
		ascending: true,
	});

	return (
		<div>
			<select
				value={filters.category}
				onChange={(e) =>
					setFilters({
						...filters,
						category: e.target.value,
					})
				}
			>
				<option value="all">All</option>
				<option value="active">Active</option>
			</select>
		</div>
	);
}

Requirements

  • React ≥16.8.0
  • Next.js ≥13.0.0

License

MIT