Package Exports
- @davstack/use-url
- @davstack/use-url/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@davstack/use-url) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
🌐 useUrl: Next.js URL State Management 🔗
Easily read and write complex data types as URL query parameters
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.