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-query-string

v2.4.1

Published

A React hook that serializes state into the URL query string

Downloads

3,527

Readme

useQueryString

Build Status

A React hook that serializes state into the URL query string

Installation

$ npm install use-query-string

Usage

Given a location object and a history updater function, this hook will return an array who's first element is an object representing the current URL query string. The second element in the array is a function that serializes an object into the query string and updates the former query object.

import useQueryString from 'use-query-string';

const [query, setQuery] = useQueryString(location, updateQuery);

The first argument passed to the hook is a Location object, and the second is a history-updating function with the following signature:

(path: string): void => {
  // update the browser history
}

Configuration

parseOptions

You can supply an optional third argument to the hook that gets passed along as options to the parse function. These allow you to do things like automatically convert values to numbers or booleans, when appropriate. See the query-string docs for all of the accepted options.

const [query, setQuery] = useQueryString(
  location,
  navigate,
  {
    parseNumbers: true,
    parseBooleans: true
  }
);

stringifyOptions

You can also pass a fourth argument to the hook that gets used as options for the stringify function that serializes your state. This is especially useful if you need to serialize/deserialize arrays a way other than the default. See the query-string docs for all of the accepted options.

const arrayFormat = 'comma';
const [query, setQuery] = useQueryString(
  location,
  navigate,
  {arrayFormat},
  {
    skipNull: true,
    arrayFormat
  }
);

Examples

In this example, you'll see a component using the query string to serialize some state about a selected color. The component uses the global Location object, and a function that calls History.pushState to update the page URL.

import React from 'react';
import useQueryString from 'use-query-string';

function updateQuery(path) {
  window.history.pushState(null, document.title, path);
}

function ColorPicker() {
  const [{color}, setQuery] = useQueryString(
    window.location,
    updateQuery
  );

  function handleColorChange(event) {
    setQuery({color: event.target.value});
  }

  return (
    <div>
      <p style={{color}}>Color is {color}</p>
      <select value={color} onChange={handleColorChange}>
        <option value="red">Red</option>
        <option value="blue">Blue</option>
      </select>
    </div>
  );
}

Gatsby example

If you're using Gatsby, you could pass props.location and the navigate helper function from Gatsby Link as arguments to the hook.

// pages/index.js
import React from 'react';
import useQueryString from 'use-query-string';
import {navigate} from 'gatsby';

function Home(props) {
  const [query, setQuery] = useQueryString(
    props.location, // pages are given a location object via props
    navigate
  );

  // ...the rest of your page
}

Practical example

The following CodeSandbox contains an example for working with multiple boolean filters that change something in the page and persist between reloads.

Edit zen-stallman-6r908

An example using context

When building a complex app, you may have multiple components within a page that need to read from and write to the query string. In these cases, using a useQueryString hook in each component will cause your query string to fall out of sync, since each invocation of the hook manages its own internal state.

To avoid this issue, use context to pass query and setQuery to descendant components within a page.

// src/pages/billing.js
import React, {createContext, useContext} from 'react';
import useQueryString from 'use-query-string';
import {navigate} from 'gatsby';

// create context to use in parent and child components
const QueryStringContext = createContext();

export default function Billing(props) {
  const [query, setQuery] = useQueryString(props.location, navigate);
  return (
    <QueryStringContext.Provider value={{query, setQuery}}>
      <div>
        <FilterInput name="client" />
        <FilterInput name="industry" />
        <FilterInput name="email" />
      </div>
      {/* render table of filtered data */}
    </QueryStringContext.Provider>
  );
}

function FilterInput(props) {
  const {query, setQuery} = useContext(QueryStringContext);

  function handleChange(event) {
    const {name, value} = event.target;
    setQuery({[name]: value});
  }

  return (
    <input
      name={props.name}
      value={query[props.name]}
      onChange={handleChange}
    />
  );
}

Edit Nested components example

License

MIT