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

use-url-search-params

v2.5.1

Published

[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/rudyhuynh/use-url-search-params/blob/master/License)

Downloads

14,056

Readme

useUrlSearchParams()

GitHub license

A React Hook to use URL query string as a state management

Demo

Why you need this

  • Your app need to persist its state after user refresh the page (used for simple, non-sensitive data).
  • Some page settings (ex: table filter, sorting, paging, etc.) should be saved in the URL so that user can easily pass to others. e.g. Tester can easily send a URL of a page to developer with very least reproduce steps.
  • You want to do something (request new data, etc.) every time some URL query value changes.
  • Combine all of the above with a URL query as a single source of truth.

Installation

npm install use-url-search-params

or

yarn add use-url-search-params

How to use

For most of the time you will do something like this:

import React from "react";
import { useUrlSearchParams } from "use-url-search-params";

function App() {
  // Your page URL will be like this by default: http://my.page?checked=true
  const [params, setParams] = useUrlSearchParams({ checked: true });

  React.useEffect(() => {
    // do something when `params.checked` is updated.
  }, [params.checked]);

  return (
    <div>
      <input type="checkbox" checked={params.checked} onChange={(e) => setParams({ checked: e.target.checked })} />
    </div>
  );
}

How to control the value parsed from URL query

By default, all values parsed from URL query are string. In case you want to get boolean or number value, pass a second argument to useUrlSearchParams() to specify data type you want to get from params object. Here is an example:

const initial = {
  y: "option1",
};
const types = {
  x: Number,
  y: Boolean,
  z: Date,
  t: ["option1", "option2", "option3"],
};
const [params, setParams] = useUrlSearchParams(initial, types);

// `params.x` will be number (or NaN)
// `params.y` will be one of [undefined, true, false]
// `params.z` will be instance of Date (can be Invalid Date)
// `params.t` will be one of ["option1", "option2", "option3"] (can be `undefined` if not specified in `initial`)

Complex data structure

Although you can use JSON.parse() and JSON.stringify() to get/set arbitrary serializable data to URL query, it is not recommended. URL query is a good place to store and persist page settings as key/value pairs such as table filter, sorting, paging, etc. We should keep it that way for simplicity. For complex data structure, you should consider using other state management for better performance, security and flexibility.

WARNING: Be aware of XSS attack. Be careful to validate values from URL query before using it by either using types - the second parameter passed to useUrlSearchParams() or validate them yourself if neccessary.

But if you still insist, here is an example:

function App() {
  const [params, setParams] = useUrlSearchParams(
    {},
    {
      complexData: (dataString) => {
        try {
          return JSON.parse(dataString);
        } catch (e) {
          return {};
        }
      },
    }
  );

  const onSetParams = (data) => {
    setParams({ complexData: JSON.stringify(data) });
  };

  return <div>{/*...*/}</div>;
}

React Router

Should just work with React Router or any routing system. Just make sure that your component re-render whenever route changes.

API

  • useUrlSearchParams([initial, types, replace])
    • initial (optional | Object): To set default values for URL query string.
    • types (optional | Object): Has similar shape with initial, help to resolve values from URL query string. Supported types:
      • String (default)
      • Number
      • Bool
      • Date - Date​.prototype​.toISOString() is used to parse date to string, e.g date string in your URL query is zero UTC offset
      • Array of available string values (like enum)
      • A custom resolver function
    • replace (optional | boolean | default: false): If true, will call histor#replaceState() instead of history#pushState() on url search param change.

Read more (for maintainers)

This library is built base on URLSearchParams interface

License

MIT