All Projects β†’ trevorblades β†’ use-query-string

trevorblades / use-query-string

Licence: MIT license
πŸ†™ A React hook that serializes state into the URL query string

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to use-query-string

react-cool-form
😎 πŸ“‹ React hooks for forms state and validation, less code more performant.
Stars: ✭ 246 (+392%)
Mutual labels:  hooks, state-management, react-hooks
jedisdb
redis like key-value state management solution for React
Stars: ✭ 13 (-74%)
Mutual labels:  hooks, state-management, react-hooks
resynced
An experimental hook that lets you have multiple components using multiple synced states using no context provider
Stars: ✭ 19 (-62%)
Mutual labels:  hooks, state-management, react-hooks
atomic-state
A decentralized state management library for React
Stars: ✭ 54 (+8%)
Mutual labels:  hooks, state-management, react-hooks
Constate
React Context + State
Stars: ✭ 3,519 (+6938%)
Mutual labels:  hooks, state-management, react-hooks
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+8950%)
Mutual labels:  hooks, state-management, react-hooks
use-app-state
🌏 useAppState() hook. that global version of setState() built on Context.
Stars: ✭ 65 (+30%)
Mutual labels:  hooks, state-management, react-hooks
niue
A tiny shared state and event library for React
Stars: ✭ 17 (-66%)
Mutual labels:  state-management, react-hooks
react-ui-hooks
🧩Simple repository of React hooks for building UI components
Stars: ✭ 20 (-60%)
Mutual labels:  hooks, react-hooks
react-without-redux
React State Management without Redux
Stars: ✭ 33 (-34%)
Mutual labels:  state-management, react-hooks
react-breakpoints
Respond to changes in a DOM element's size. With React Breakpoints, element queries are no longer "web design's unicorn" πŸ¦„
Stars: ✭ 74 (+48%)
Mutual labels:  hooks, react-hooks
react-mlyn
react bindings to mlyn
Stars: ✭ 19 (-62%)
Mutual labels:  state-management, react-hooks
react-immer
No nonsense state management with Immer and React hooks
Stars: ✭ 13 (-74%)
Mutual labels:  state-management, react-hooks
dobux
πŸƒ Lightweight responsive state management solution.
Stars: ✭ 75 (+50%)
Mutual labels:  hooks, state-management
rex-state
Convert hooks into shared states between React components
Stars: ✭ 32 (-36%)
Mutual labels:  state-management, react-hooks
useSharedState
useSharedState is a simple hook that can be used to share state between multiple React components.
Stars: ✭ 0 (-100%)
Mutual labels:  hooks, state-management
use-route-as-state
Use React Router route and query string as component state
Stars: ✭ 37 (-26%)
Mutual labels:  querystring, react-hooks
react-use-comlink
Three ways to use Comlink web workers through React Hooks (and in a typesafe manner).
Stars: ✭ 39 (-22%)
Mutual labels:  hooks, react-hooks
concave
🧐 Lens-like state management (for React).
Stars: ✭ 13 (-74%)
Mutual labels:  state-management, react-hooks
flhooks
React like Hooks implementation for Flutter.
Stars: ✭ 38 (-24%)
Mutual labels:  hooks, react-hooks

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].