useSearchState
is used similarly to useState
in that it returns a value and setter.
The simplest use case is to tie the value to the search params with a key.
MyComponent.tsx
import useSearchState from './useSearchState'
const MyComponent = () => {
const [value, setValue] = useSearchState('value')
return (<>
<button onClick={()=>setValue('red')} className={value==='red'?'active':''}>Red</button>
<button onClick={()=>setValue('blue')} className={value==='blue'?'active':''}>Blue</button>
</>)
}
export default MyComponent
The default type is string|undefined
, but by providing an unset
argument, the type can be number
or boolean
.
const [num, setNum] = useSearchState('num', 0)
const [flag, setFlag] = useSearchState('flag', false)
If setValue
is called with the unset
value, the key is removed from the search params.
parameter | type | description |
---|---|---|
name | string |
Key in search params |
unset | any |
Value to use if the name is unset in the search params. default type is string|undefined |
options.format | function |
For encoding the value into the search params. Default is x.toString() |
options.parse | function |
For decoding the value from the search params. Default handles number|boolean|string |
Returns [value, setValue]
like useState()