Skip to content

yuanfux/use-query-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useQueryState

🎣 use Query String as State

Preivew

View Demo

useQueryState is a React Hook that helps to bind Query String with React State and makes every user action memorizable.

Prerequisite

  • react ^16.8.0
  • react-router-dom ^5.1.0

Install

npm install use-query-state

Usage

just like using setState

Basic

import useQueryState from 'use-query-state';

const App = () => {
  const [number, setNumber] = useQueryState(0, 'number');
  const random = () => {
    setNumber(Math.floor(Math.random() * 100));
  };
  return (
    <div>
      <div>{number}</div>
      <button onClick={random}>Random Number</button>
    </div>
  );
};

Edit Basic Example

Advanced

import useQueryState from 'use-query-state';

const App = () => {
  const [input, setInput] = useQueryState('hello world', 'input', { action: 'replace', delay: 300 });
  const onInputChange = (event) => {
    setInput(event.target.value);
  };
  return (
    <div>
      <input value={input} onChange={onInputChange} />
    </div>
  );
}

Edit Advanced Example

API

useQueryState(DefaultValue, QueryParamName, Options? ): [Value, Setter]

DefaultValue

  • Type: string | boolean | number | string[]
  • Required: true
  • Description: the value is used when query parameter is undefined

QueryParamName

  • Type: string
  • Required: true
  • Description: the value is used as the query parameter name

Options

  • Type:
    {
      action?: 'push' | 'replace',
      delay?: number 
    }
  • Required: false
  • Description:
    • action is defining how to mutate the history state
      action defaults to 'push'
    • delay is defining the debounce wait time for mutating the history state when using Setter
      delay defaults to 0.

Value

  • Type: string | boolean | number | string[] | undefined | null
  • Description: the returned value for read

Setter

  • Type: (value: Value): void
  • Description: The setter used for setting the state

License

MIT

About

🎣 use query string as state

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published