@thibault.sh/hooks
Version:
A comprehensive collection of React hooks for browser storage, UI interactions, and more
52 lines (50 loc) • 1.81 kB
text/typescript
/**
* Hook that manages state synchronized with URL query parameters.
*
* Automatically persists state to the URL and keeps it in sync with browser
* navigation (back/forward buttons). Perfect for shareable URLs and maintaining
* state across page refreshes.
*
* @template T - The type of the state value
* @param key - The query parameter key to use in the URL
* @param initialValue - Default value when the parameter doesn't exist
* @param options - Configuration options for serialization
* @param options.serialize - Custom function to convert value to string (defaults to JSON.stringify)
* @param options.deserialize - Custom function to parse string back to value (defaults to JSON.parse)
*
* @returns A tuple containing:
* - Current state value (synced with URL)
* - Setter function (updates both state and URL)
*
* @example
* ```tsx
* function SearchPage() {
* const [query, setQuery] = useQueryParamsState('q', '');
* const [filters, setFilters] = useQueryParamsState('filters', { category: 'all' });
*
* return (
* <div>
* <input
* value={query}
* onChange={(e) => setQuery(e.target.value)}
* placeholder="Search..."
* />
* <select
* value={filters.category}
* onChange={(e) => setFilters({ ...filters, category: e.target.value })}
* >
* <option value="all">All</option>
* <option value="books">Books</option>
* </select>
* </div>
* );
* }
* ```
*
* @see https://thibault.sh/hooks/use-query-params-state
*/
declare function useQueryParamsState<T>(key: string, initialValue: T, options?: {
serialize?: (value: T) => string;
deserialize?: (value: string) => T;
}): [T, (value: T | ((val: T) => T)) => void];
export { useQueryParamsState };