@hunab/react-url-sync
v1.0.1
Published
A simple React hook to synchronize component state with URL query parameters.
Downloads
4
Maintainers
Readme
@hunab/react-url-sync
A simple React hook to synchronize component state with URL query parameters.
✨ Features
- 🔗 Synchronize state with URL query parameters.
- 🎣 Easy-to-use React hook API.
- ⚡ Zero dependencies (only React).
- 📦 Lightweight and tree-shakeable.
📦 Installation
npm install @hunab/react-url-sync
# or
yarn add @hunab/react-url-sync
# or
pnpm add @hunab/react-url-sync🚀 Usage
Here's a simple example of how to sync a search input with the URL:
import React from 'react';
import { useUrlState } from '@hunab/react-url-sync';
function SearchComponent() {
// The 'searchTerm' state will be synced with the 'q' parameter in the URL
const [searchTerm, setSearchTerm] = useUrlState('q', '');
return (
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search..."
/>
);
}🛠 API
useUrlState(key: string, defaultValue: T)
- key: The name of the query parameter in the URL.
- defaultValue: Default state value when the parameter is missing.
Returns
[T, React.Dispatch<React.SetStateAction<T>>]📖 Examples
Multiple parameters
const [page, setPage] = useUrlState('page', 1);
const [filter, setFilter] = useUrlState('filter', 'all');🤝 Contributing
Contributions, issues and feature requests are welcome!
Feel free to check the issues page.
📄 License
This project is licensed under the MIT License.
