🎣 use Query String as State
View Demo
useQueryState
is a React Hook that helps to bind Query String with React State and makes every user action memorizable.
- react ^16.8.0
- react-router-dom ^5.1.0
npm install use-query-state
just like using
setState
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>
);
};
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>
);
}
- Type:
string
|boolean
|number
|string[]
- Required:
true
- Description: the value is used when query parameter is
undefined
- Type:
string
- Required:
true
- Description: the value is used as the query parameter name
- 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 usingSetter
delay
defaults to0
.
- Type:
string
|boolean
|number
|string[]
|undefined
|null
- Description: the returned value for read
- Type:
(value: Value): void
- Description: The setter used for setting the state
MIT