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.
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.
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
npm install use-query-sync
const [state, setState] = useUrlState(initialState, options?)
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)
state
: Current state valuesetState
: Function to update state and URL
function SearchBar() {
const [query, setQuery] = useUrlState("", { name: "search" });
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
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>
);
}
- React ≥16.8.0
- Next.js ≥13.0.0
MIT