JSPM

  • Created
  • Published
  • Downloads 24604
  • Score
    100M100P100Q163100F
  • License MIT

Easily share complex state objects between unrelated React components, preserve types and structure, with TS validation. Deep links and url state synchronization wthout any hasssle or boilerplate.

Package Exports

  • state-in-url
  • state-in-url/encodeState
  • state-in-url/encoder
  • state-in-url/next
  • state-in-url/react-router
  • state-in-url/useSharedState
  • state-in-url/useUrlEncode
  • state-in-url/useUrlStateBase
  • state-in-url/utils

Readme

English | 한국어 | 简体中文

state-in-url logo

Easily share complex state objects between unrelated React components, preserve types and structure, with TS validation. Without any hasssle or boilerplate.



npm Tests Codacy Badge Commitizen friendly semantic-release: angular npm bundle size (minified + gzip)

Don't hesitate to open an issue if you found a bug, or for requesting features

Demo-gif

DEMO | DEMO2


Add a ⭐️ and follow me to support the project!

Will appreciate you feedback/opinion on discussions

Share if it useful for you. FB LinkedIn X.com VK


Why use state-in-url?

state-in-url Simple state management with optional URL sync. Good for implementing deep links. Share complex states between unrelated React components, TS-friendly, NextJS compatible. Most of users don't care about URL, so, can use it to store your app state.

Use cases

  • 🧮 Store unsaved user forms in URL
  • 🙃 Share the state between different components without changing url, good as alternative to signals and other state management tools
  • 🧠 Sync data between unrelated client components
  • 🔗 Shareable URLs with application state (Deep linking, URL state synchronization)
  • 🔄 Easy state persistence across page reloads

Features

  • 🧩 Simple: No providers, reducers, boilerplate or new concepts, API similar to React.useState
  • 📘 Typescript support and type Safety: Preserves data types and structure, good developer experience with IDE suggestions, strong typing and JSDoc comments
  • ⚛️ Framework Flexibility: Separate hooks for Next.js and React.js applications, and functions for pure JS
  • Well tested: Unit tests and Playwright tests, high quality and support
  • Fast: Minimal rerenders, less than 1ms to encode and decode an object
  • 🪶 Lightweight: Zero dependencies for a smaller footprint

Table of content

installation

1. Install package

# npm
npm install --save state-in-url
# yarn
yarn add state-in-url
# pnpm
pnpm add state-in-url

2. Edit tsconfig.json

In tsconfig.json in compilerOptions set "moduleResolution": "Bundler", or"moduleResolution": "Node16", or "moduleResolution": "NodeNext". Possibly need to set "module": "ES2022", or "module": "ESNext"

useUrlState

useUrlState is a custom React hook for Next.js/React-Router applications that make communication between client components easy. It allows you to share any complex state and sync it with the URL search parameters, providing a way to persist state across page reloads and share application state via URLs.

useUrlState hook for Next.js

Docs

React-Router example

Usage examples

Basic

  1. Define state shape

    // userState.ts
    // State shape should be stored in a constant, don't pass an object directly
    export const userState: UserState = { name: '', age: 0 }
    
    type UserState = { name: string, age: number }
  2. Import it and use

'use client'
import { useUrlState } from 'state-in-url/next';

import { userState } from './userState';

function MyComponent() {
  // can pass `replace` arg, it's control will `setUrl` will use `rounter.push` or `router.replace`, default replace=true
  // can pass `searchParams` from server components
  const { urlState, setUrl, setUrlState } = useUrlState({ defaultState: userState });

  // won't let you to accidently mutate state directly, requires TS
  // urlState.name = 'John' // <- error

  return (
    <div>
      <input value={urlState.name}
        onChange={(ev) => { setUrl({ name: ev.target.value }) }}
      />
      <input value={urlState.age}
        onChange={(ev) => { setUrl({ age: +ev.target.value }) }}
      />

      // same api as React.useState
      <input value={urlState.name}
        onChange={(ev) => { setUrlState(curr => ({ ...curr, name: ev.target.value })) }}
        // Can update state immediately but sync change to url as needed
        onBlur={() => setUrl()}
      />

      <button onClick={() => setUrl(userState)}>
        Reset
      </button>

    </div>
  )
}

With complex state shape

Example
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';

function TagsComponent() {
  // `urlState` will infer from Form type!
  const { urlState, setUrl } = useUrlState({ defaultState: form });

  const onChangeTags = React.useCallback(
    (tag: (typeof tags)[number]) => {
      setUrl((curr) => ({
        ...curr,
        tags: curr.tags.find((t) => t.id === tag.id)
          ? curr.tags.filter((t) => t.id !== tag.id)
          : curr.tags.concat(tag),
      }));
    },
    [setUrl],
  );

  return (
    <div>
      <Field text="Tags">
        <div className="flex flex-wrap gap-2">
          {tags.map((tag) => (
            <Tag
              active={!!urlState.tags.find((t) => t.id === tag.id)}
              text={tag.value.text}
              onClick={() => onChangeTags(tag)}
              key={tag.id}
            />
          ))}
        </div>
      </Field>
    </div>
  );
}

const tags = [
  {
    id: '1',
    value: { text: 'React.js', time: new Date('2024-07-17T04:53:17.000Z') },
  },
  {
    id: '2',
    value: { text: 'Next.js', time: new Date('2024-07-18T04:53:17.000Z') },
  },
  {
    id: '3',
    value: { text: 'TailwindCSS', time: new Date('2024-07-19T04:53:17.000Z') },
  },
];

Demo page example code

Update state only and sync to URL manually

Example
const timer = React.useRef(0 as unknown as NodeJS.Timeout);
React.useEffect(() => {
  clearTimeout(timer.current);
  timer.current = setTimeout(() => {
    // will compare state by content not by reference and fire update only for new values
    setUrl(urlState);
  }, 500);

  return () => {
    clearTimeout(timer.current);
  };
}, [urlState, setUrl]);

Syncing state onBlur will be more aligned with real world usage.

<input onBlur={() => updateUrl()} .../>

With server side rendering

Example
export default async function Home({ searchParams }: { searchParams: object }) {
  return (
    <Form searchParams={searchParams} />
  )
}

// Form.tsx
'use client'
import React from 'react';
import { useUrlState } from 'state-in-url/next';
import { form } from './form';

const Form = ({ searchParams }: { searchParams: object }) => {
  const { urlState, setState, setUrl } = useUrlState({ defaultState: form, searchParams });
}

Using hook in layout component

Example That a tricky part, since nextjs with app router doesn't allow to access searchParams from server side. There is workaround with using middleware, but it isn't pretty and can stop working after nextjs update.
// add to appropriate `layout.tsc`
export const runtime = 'edge';

// middleware.ts
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const url = request.url?.includes('_next') ? null : request.url;
  const sp = url?.split?.('?')?.[1] || '';

  const response = NextResponse.next();

  if (url !== null) {
    response.headers.set('searchParams', sp);
  }

  return response;
}

// Target layout component
import { headers } from 'next/headers';
import { decodeState } from 'state-in-url/encodeState';

export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  const sp = headers().get('searchParams') || '';

  return (
    <div>
      <Comp1 searchParams={decodeState(sp, stateShape)} />
      {children}
    </div>
  );
}

Example
'use client'
import { useUrlState } from 'state-in-url/next';

const someObj = {};

function SettingsComponent() {
  const { urlState, setUrl, setState } = useUrlState<object>(someObj);
}

useUrlState hook for React-Router

API is same as for Next.js version, except can pass options from NavigateOptions type.

Docs

Example

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 } }[];
};
import { useUrlState } from 'state-in-url/react-router';

import { form } from './form';

function TagsComponent() {
  const { urlState, setUrl, setUrlState } = useUrlState({ defaultState: form });

  const onChangeTags = React.useCallback(
    (tag: (typeof tags)[number]) => {
      setUrl((curr) => ({
        ...curr,
        tags: curr.tags.find((t) => t.id === tag.id)
          ? curr.tags.filter((t) => t.id !== tag.id)
          : curr.tags.concat(tag),
      }));
    },
    [setUrl],
  );

  return (
    <div>
      <Field text="Tags">
        <div className="flex flex-wrap gap-2">
          {tags.map((tag) => (
            <Tag
              active={!!urlState.tags.find((t) => t.id === tag.id)}
              text={tag.value.text}
              onClick={() => onChangeTags(tag)}
              key={tag.id}
            />
          ))}
        </div>
      </Field>

      <input value={urlState.name}
        onChange={(ev) => { setUrlState(curr => ({ ...curr, name: ev.target.value })) }}
        // Can update state immediately but sync change to url as needed
        onBlur={() => setUrl()}
      />
    </div>
  );
}

const tags = [
  {
    id: '1',
    value: { text: 'React.js', time: new Date('2024-07-17T04:53:17.000Z') },
  },
  {
    id: '2',
    value: { text: 'Next.js', time: new Date('2024-07-18T04:53:17.000Z') },
  },
  {
    id: '3',
    value: { text: 'TailwindCSS', time: new Date('2024-07-19T04:53:17.000Z') },
  },
];

Example code

Other hooks and helpers

useUrlStateBase hook for others routers

Hooks to create your own useUrlState hooks with other routers, e.g. react-router or tanstack router.

Docs

useSharedState hook for React.js

Hook to share state between any React components, tested with Next.js and Vite.

'use client'
import { useSharedState } from 'state-in-url';

export const someState = { name: '' };

function SettingsComponent() {
  const { state, setState } = useSharedState(someState);
}

Docs

useUrlEncode hook for React.js

Docs

encodeState and decodeState helpers

Docs

encode and decode helpers

Docs

Best Practices

  • Define your state shape as a constant
  • Use TypeScript for enhanced type safety and autocomplete
  • Avoid storing sensitive information in URL parameters (SSN, API keys etc)
  • Use this extension for readable TS errors

Gothas

  1. Can pass only serializable values, Function, BigInt or Symbol won't work, probably things like ArrayBuffer neither. Everything that can be serialized to JSON will work.
  2. Vercel servers limit size of headers (query string and other stuff) to 14KB, so keep your URL state under ~5000 words. https://vercel.com/docs/errors/URL_TOO_LONG
  3. Tested with next.js 14/15 with app router, no plans to support pages.

Other

Contribute and/or run locally

See Contributing doc

Roadmap

  • hook for Next.js
  • hook for 'react-router`
  • hook for 'remix`
  • hook for store state in hash ?

Contact & Support

  • Create a GitHub issue for bug reports, feature requests, or questions

Changelog

License

This project is licensed under the MIT license.

Inspiration

NUQS

Using URL to store state in Vue

Storing state in the URL

NextJS useSearchParams