@davstack/use-url
v1.0.7
Published
A custom hook for easily reading and writing all data types from url search params
Downloads
3
Maintainers
Readme
Features
- 🌐 Simplified global state management: the URL serves as the single source of truth.
- 🔗 Supports Arrays, Objects, Arrays of Objects, Dates, and primitive data types.
- 🟦 Supports TypeScript, with custom param types.
Installation
npm install @davstack/use-url
or
pnpm add @davstack/use-url
or
yarn add @davstack/use-url
Usage
import { useUrl } from '@davstack/use-url';
export default () => {
const { params, setParam } = useUrl();
const { name } = params;
return (
<>
<h1>Hello, {name || 'anonymous visitor'}!</h1>
<input value={name || ''}
onChange={()=>setParam('name', e.target.value))}
/>
<button
onClick={() => setParam('name', null)}
>
Clear
</button>
</>
);
};
Example: simple counter stored in the URL:
import React from 'react';
import { useUrl } from '@davstack/use-url';
export default function CounterComponent() {
const { params, setParam } = useUrl();
const handleReset = () => setParam('count', 0);
const handleIncrement = () => setParam('count', (c) => c ?? 0 + 1);
const handleDecrement = () => setParam('count', (c) => c ?? 0 - 1);
const handleClear = () => setParam('count', null);
return (
<>
<pre>count: {count ?? 'Not set'}</pre>
<button onClick={handleReset}>Reset</button>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
<button onClick={handleClear}>Clear</button>
</>
);
}
Types
import { Params } from '@davstack/use-url';
declare module '@davstack/use-url' {
export interface Params {
startDate: Date;
endDate: Date;
//... add custom properties here
}
}
Caveats
Because the Next.js router is not available in an SSR context, this
hook will always return null
(or the default value if supplied) on SSR/SSG.