State in url
State management and deep links
State management and deep links
Share complex state between unrelated React.js components and sync it to the URL
{ "name": "", "agree to terms": false, "tags": [] }
export const form: Form = {
name: '',
age: undefined,
'agree to terms': false,
tags: [],
};
type Form = {
name: string;
age?: number;
'agree to terms': boolean;
tags: { id: string; value: { text: string; time: Date } }[];
};
'use client';
import { useUrlState } from 'state-in-url/next';
import { form } from './form';
export const ComponentA = () => {
const { state, updateUrl, updateState } = useUrlState({ defaultState: form });
return <input
id="name"
value={state.name}
onChange={(ev) => updateState({ name: ev.target.value })}
onBlur={() => updateUrl()}
/>
};
'use client';
import { useUrlState } from 'state-in-url/next';
import { form } from './form';
// "searchParams" used to pass params from Server Components
export const ComponentB = ({ searchParams }: { searchParams?: object }) => {
const { state } = useUrlState({ defaultState: form, searchParams });
return <div>name: {state.name}</div>
};