JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 24
  • Score
    100M100P100Q60015F
  • License MIT

React hook for managing state in the URL

Package Exports

  • react-use-url-state

Readme

react-use-url-state

Use URL to store a state in React.

  • Easily handle numbers, dates, booleans, and arrays.
  • Have a type-safety with Zod

Installation

pnpm add react-use-url-state zod
npm i react-use-url-state zod

Documentation

📝Documentation and examples

Usage

It's important to use .coerce on your Zod schema to ensure that the values are parsed correctly from the URL.

function MyComponent() {
  const { data, setState, setValue, isError, error } = useUrlState(
    z.object({
      name: z.string(),
      age: z.coerce.number(),
      birthDate: z.coerce.date().optional(),
    }),
  );

  return <div>
    <Button
      onClick={() => {
        setState({ name: 'test', age: 10, birthDate: new Date() });
      }}
    >
      Set state
    </Button>

    <Button
      onClick={() => {
        setValue('age', data.age + 1);
      }}
    >
      Increment age
    </Button>

    <pre>{JSON.stringify(data, null, 2)}</pre>
  </div>
}

🚧 TODO

  • Add automatic tests
  • Add routers without polling for Next App/Page