@davstack/use-url
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

🌐 useUrl: Next.js URL State Management 🔗

Easily read and write complex data types as URL query parameters


NPM Continuous Integration


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.

Package Sidebar

Install

npm i @davstack/use-url

Weekly Downloads

0

Version

1.0.7

License

ISC

Unpacked Size

21.3 kB

Total Files

14

Last publish

Collaborators

  • dawidwraga