npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@scr2em/react-router-sync-state

v1.0.8

Published

Here's a full documentation for the `react-router-sync-state` package:

Downloads

273

Readme

Here's a full documentation for the react-router-sync-state package:

A collection of React hooks for managing state in the URL search parameters.

Installation

To install the package, run the following command:

npm install @scr2em/react-router-sync-state

Usage

This package provides several hooks to manage different types of state in the URL:

  1. useStringState
  2. useNumberState
  3. useBooleanState
  4. useMultiStringState
  5. useMultiNumberState

Each hook allows you to synchronize state with URL search parameters, providing a seamless way to manage application state through the URL.

useStringState

This hook manages a string value in the URL.

import { useStringState } from '@scr2em/react-router-sync-state';

function StringExample() {
  const [value, setValue] = useStringState("name", {
    defaultValue: "john",
  });

  return (
      <input
        value={value}
        type="text"
        onInput={(e) => {
            setValue(e.target.value as string);
        }}
      />
  );
}

You can also use the hook with a validator function to validate the URL parameter value, if the value in the url doesn't match the validator function, it will fall back to the default value

import { useStringState } from '@scr2em/react-router-sync-state';

enum Cars {
	BMW = "bmw",
	AUDI = "audi",
	MERCEDES = "mercedes",
}

function StringExample() {
  const [value, setValue] = useStringState("cars", {
	defaultValue: Cars.BMW,
	validator: (value) : value is Cars => Object.values(Cars).includes(value as Cars)
  });

  return (
	  <input
		value={value} // value of type Cars
		type="text"
		onInput={(e) => {
			setValue(e.target.value as string);
		}}
	  />
  );
}

useNumberState

This hook manages a number value in the URL.

import { useNumberState } from '@scr2em/react-router-sync-state';

function NumberExample() {
  const [value, setValue] = useNumberState("page", { defaultValue: 1 });

  return (
      <input
        value={value}
        type="number"
        onInput={(e) => {
            setValue(Number(e.target.value));
        }}
      />
  );
}

useBooleanState

This hook manages a boolean value in the URL.

import { useBooleanState } from '@scr2em/react-router-sync-state';

function BooleanExample() {
  const [value, setValue, toggle] = useBooleanState("toggle", { defaultValue: true });

  return (
    <div>
      <h1>Boolean State: {value.toString()}</h1>
      <button onClick={() => toggle()}>Toggle</button>
    </div>
  );
}

useMultiStringState

This hook manages an array of strings in the URL.

import { useMultiStringState } from '@scr2em/react-router-sync-state';

function MultiStringExample() {
  const [value, setValue] = useMultiStringState("tags", {
    defaultValue: ["react", "hooks"],
    delimiter: ","
  });

  return (
    <div>
      {value.map((tag, index) => (
        <span key={index}>{tag}</span>
      ))}
      <button onClick={() => setValue([...value, "newTag"])}>Add Tag</button>
    </div>
  );
}

useMultiNumberState

This hook manages an array of numbers in the URL.

import { useMultiNumberState } from '@scr2em/react-router-sync-state';

function MultiNumberExample() {
  const [value, setValue] = useMultiNumberState("ids", {
    defaultValue: [1, 2, 3],
    delimiter: "-"
  });

  return (
    <div>
      {value.map((id, index) => (
        <span key={index}>{id}</span>
      ))}
      <button onClick={() => setValue([...value, value.length + 1])}>Add ID</button>
    </div>
  );
}

API Reference

Each hook returns an array [value, set, toggle] where:

  • value: The current value of the state.
  • set: A function to update the state value.
  • toggle: (Only for useBooleanState) A function to toggle the boolean value.

Each hook accepts the following parameters:

  1. searchParamName: The name of the URL search parameter to use.
  2. options: An object containing:
    • defaultValue: The default value to use when the URL parameter is not set.
    • delimiter: (Only for multi-value hooks) The delimiter to use when joining/splitting array values in the URL.

Notes

  • The hooks automatically sync the state with the URL, updating the URL when the state changes and vice versa.
  • When the state is set to its default value, the corresponding URL parameter is removed to keep the URL clean.
  • Invalid URL parameters are automatically removed and replaced with the default value.

Requirements

This package requires React 18 or later and react-router-dom 6 or later as peer dependencies.

License

This project is licensed under the ISC License.