use-query-sync
v1.0.2
Published
React hook for synchronizing state with URL query parameters
Maintainers
Readme
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-syncAPI
const [state, setState] = useUrlState(initialState, options?)Parameters
initialState: The initial state value (any serializable value)options: Optional configuration objectname: Query parameter name (defaults to 'q')initFromQuery: Whether to initialize from URL (defaults to true)
Returns
state: Current state valuesetState: 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
