Gathering detailed insights and metrics for use-query-params
Gathering detailed insights and metrics for use-query-params
Gathering detailed insights and metrics for use-query-params
Gathering detailed insights and metrics for use-query-params
use-url-search-params
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/rudyhuynh/use-url-search-params/blob/master/License)
@scaleway/use-query-params
A small hook to handle params
@kimaramyz/use-query-params
React hooks for using URL query params as state. No dependencies.
gatsby-plugin-use-query-params
Drop in support for [`use-query-params`](https://www.npmjs.com/package/use-query-params)
React Hook for managing state in URL query parameters with easy serialization.
npm install use-query-params
Typescript
Module System
Node Version
NPM Version
90.6
Supply Chain
94.8
Quality
74.9
Maintenance
100
Vulnerability
99.6
License
v2.2.1
Published on 24 Mar 2023
v2.2.0
Published on 08 Feb 2023
v2.1.1
Published on 17 Sept 2022
v2.1.0
Published on 31 Aug 2022
v2.0.1
Published on 31 Aug 2022
v2.0.0
Published on 16 Aug 2022
TypeScript (98.52%)
JavaScript (1.48%)
Total Downloads
45,719,931
Last Day
58,909
Last Week
245,373
Last Month
1,081,546
Last Year
14,137,875
2,183 Stars
357 Commits
97 Forks
14 Watching
8 Branches
29 Contributors
Minified
Minified + Gzipped
Latest Version
2.2.1
Package Id
use-query-params@2.2.1
Unpacked Size
286.00 kB
Size
61.24 kB
File Count
96
NPM Version
lerna/5.2.0/node@v16.15.1+x64 (darwin)
Node Version
16.15.1
Publised On
24 Mar 2023
Cumulative downloads
Total Downloads
Last day
3.6%
58,909
Compared to previous day
Last week
-12.2%
245,373
Compared to previous week
Last month
6.5%
1,081,546
Compared to previous month
Last year
7.2%
14,137,875
Compared to previous year
1
4
23
A React Hook, HOC, and Render Props solution for managing state in URL query parameters with easy serialization.
Works with React Router out of the box. TypeScript supported.
Installation | Usage | Examples | API | Demo
When creating apps with easily shareable URLs, you often want to encode state as query parameters, but all query parameters must be encoded as strings. useQueryParams
allows you to easily encode and decode data of any type as query parameters with smart memoization to prevent creating unnecessary duplicate objects. It uses serialize-query-params.
Migrating from v1? See details in the changelog.
Using npm:
$ npm install --save use-query-params
Link your routing system via an adapter (e.g., React Router 6 example, React Router 5 example):
1import React from 'react'; 2import ReactDOM from 'react-dom/client'; 3import { QueryParamProvider } from 'use-query-params'; 4import { ReactRouter6Adapter } from 'use-query-params/adapters/react-router-6'; 5import { BrowserRouter, Route, Routes } from 'react-router-dom'; 6import App from './App'; 7 8const root = ReactDOM.createRoot( 9 document.getElementById('root') as HTMLElement 10); 11root.render( 12 <BrowserRouter> 13 <QueryParamProvider adapter={ReactRouter6Adapter}> 14 <Routes> 15 <Route path="/" element={<App />}> 16 </Routes> 17 </QueryParamProvider> 18 </BrowserRouter>, 19 document.getElementById('root') 20);
By default, use-query-params uses URLSearchParams to handle interpreting the location string, which means it does not decode null
and has limited handling of other more advanced URL parameter configurations. If you want access to those features, add a third-party library like query-string and tell use-query-params to use it:
1import React from 'react'; 2import ReactDOM from 'react-dom/client'; 3import { QueryParamProvider } from 'use-query-params'; 4import { ReactRouter6Adapter } from 'use-query-params/adapters/react-router-6'; 5import { BrowserRouter, Route, Routes } from 'react-router-dom'; 6// optionally use the query-string parse / stringify functions to 7// handle more advanced cases than URLSearchParams supports. 8import { parse, stringify } from 'query-string'; 9import App from './App'; 10 11const root = ReactDOM.createRoot( 12 document.getElementById('root') as HTMLElement 13); 14root.render( 15 <BrowserRouter> 16 <QueryParamProvider 17 adapter={ReactRouter6Adapter} 18 options={{ 19 searchStringToObject: parse, 20 objectToSearchString: stringify, 21 }} 22 > 23 <Routes> 24 <Route path="/" element={<App />}> 25 </Routes> 26 </QueryParamProvider> 27 </BrowserRouter>, 28 document.getElementById('root') 29); 30
Be sure to add QueryParamProvider as shown in Installation above.
Add the hook to your component. There are two options: useQueryParam
:
1import * as React from 'react'; 2import { useQueryParam, NumberParam, StringParam } from 'use-query-params'; 3 4const UseQueryParamExample = () => { 5 // something like: ?x=123&foo=bar in the URL 6 const [num, setNum] = useQueryParam('x', NumberParam); 7 const [foo, setFoo] = useQueryParam('foo', StringParam); 8 9 return ( 10 <div> 11 <h1>num is {num}</h1> 12 <button onClick={() => setNum(Math.random())}>Change</button> 13 <h1>foo is {foo}</h1> 14 <button onClick={() => setFoo(`str${Math.random()}`)}>Change</button> 15 </div> 16 ); 17}; 18 19export default UseQueryParamExample;
Or useQueryParams
:
1import * as React from 'react'; 2import { 3 useQueryParams, 4 StringParam, 5 NumberParam, 6 ArrayParam, 7 withDefault, 8} from 'use-query-params'; 9 10// create a custom parameter with a default value 11const MyFiltersParam = withDefault(ArrayParam, []) 12 13const UseQueryParamsExample = () => { 14 // something like: ?x=123&q=foo&filters=a&filters=b&filters=c in the URL 15 const [query, setQuery] = useQueryParams({ 16 x: NumberParam, 17 q: StringParam, 18 filters: MyFiltersParam, 19 }); 20 const { x: num, q: searchQuery, filters } = query; 21 22 return ( 23 <div> 24 <h1>num is {num}</h1> 25 <button onClick={() => setQuery({ x: Math.random() })}>Change</button> 26 <h1>searchQuery is {searchQuery}</h1> 27 <h1>There are {filters.length} filters active.</h1> 28 <button 29 onClick={() => 30 setQuery( 31 { x: Math.random(), filters: [...filters, 'foo'], q: 'bar' }, 32 'push' 33 ) 34 } 35 > 36 Change All 37 </button> 38 </div> 39 ); 40}; 41 42export default UseQueryParamsExample;
1import * as React from 'react'; 2import { 3 withQueryParams, 4 StringParam, 5 NumberParam, 6 ArrayParam, 7 withDefault, 8} from 'use-query-params'; 9 10const WithQueryParamsExample = ({ query, setQuery }: any) => { 11 const { x: num, q: searchQuery, filters } = query; 12 13 return ( 14 <div> 15 <h1>num is {num}</h1> 16 <button onClick={() => setQuery({ x: Math.random() })}>Change</button> 17 <h1>searchQuery is {searchQuery}</h1> 18 <h1>There are {filters.length} filters active.</h1> 19 <button 20 onClick={() => 21 setQuery( 22 { x: Math.random(), filters: [...filters, 'foo'], q: 'bar' }, 23 'push' 24 ) 25 } 26 > 27 Change All 28 </button> 29 </div> 30 ); 31}; 32 33// create a custom parameter with a default value 34const MyFiltersParam = withDefault(ArrayParam, []) 35 36export default withQueryParams({ 37 x: NumberParam, 38 q: StringParam, 39 filters: MyFiltersParam, 40}, WithQueryParamsExample);
1import * as React from 'react'; 2import { 3 QueryParams, 4 StringParam, 5 NumberParam, 6 ArrayParam, 7 withDefault, 8} from 'use-query-params'; 9 10// create a custom parameter with a default value 11const MyFiltersParam = withDefault(ArrayParam, []) 12 13const RenderPropsExample = () => { 14 const queryConfig = { 15 x: NumberParam, 16 q: StringParam, 17 filters: MyFiltersParam, 18 }; 19 return ( 20 <div> 21 <QueryParams config={queryConfig}> 22 {({ query, setQuery }) => { 23 const { x: num, q: searchQuery, filters } = query; 24 return ( 25 <> 26 <h1>num is {num}</h1> 27 <button onClick={() => setQuery({ x: Math.random() })}> 28 Change 29 </button> 30 <h1>searchQuery is {searchQuery}</h1> 31 <h1>There are {filters.length} filters active.</h1> 32 <button 33 onClick={() => 34 setQuery( 35 { 36 x: Math.random(), 37 filters: [...filters, 'foo'], 38 q: 'bar', 39 }, 40 'push' 41 ) 42 } 43 > 44 Change All 45 </button> 46 </> 47 ); 48 }} 49 </QueryParams> 50 </div> 51 ); 52}; 53 54export default RenderPropsExample;
A few basic examples have been put together to demonstrate how useQueryParams
works with different routing systems.
For convenience, use-query-params exports all of the serialize-query-params library.
The UrlUpdateType
is a string type definings the different methods for updating the URL:
'pushIn'
: Push just a single parameter, leaving the rest as is (back button works) (the default)'push'
: Push all parameters with just those specified (back button works)'replaceIn'
: Replace just a single parameter, leaving the rest as is'replace'
: Replace all parameters with just those specifiedSee all param definitions from serialize-query-params here. You can define your own parameter types by creating an object with an encode
and a decode
function. See the existing definitions for examples.
Note that all null and empty values are typically treated as follows:
Note that with the default searchStringToObject implementation that uses URLSearchParams, null and empty values are treated as follows:
value | encoding |
---|---|
"" | ?qp= |
null | ? (removed from URL) |
undefined | ? (removed from URL) |
If you need a more discerning interpretation, you can use query-string's parse and stringify to get:
value | encoding |
---|---|
"" | ?qp= |
null | ?qp |
undefined | ? (removed from URL) |
Examples in this table assume query parameter named qp
.
Param | Type | Example Decoded | Example Encoded |
---|---|---|---|
StringParam | string | 'foo' | ?qp=foo |
NumberParam | number | 123 | ?qp=123 |
ObjectParam | { key: string } | { foo: 'bar', baz: 'zzz' } | ?qp=foo-bar_baz-zzz |
ArrayParam | string[] | ['a','b','c'] | ?qp=a&qp=b&qp=c |
JsonParam | any | { foo: 'bar' } | ?qp=%7B%22foo%22%3A%22bar%22%7D |
DateParam | Date | Date(2019, 2, 1) | ?qp=2019-03-01 |
BooleanParam | boolean | true | ?qp=1 |
NumericObjectParam | { key: number } | { foo: 1, bar: 2 } | ?qp=foo-1_bar-2 |
DelimitedArrayParam | string[] | ['a','b','c'] | ?qp=a_b_c |
DelimitedNumericArrayParam | number[] | [1, 2, 3] | ?qp=1_2_3 |
Example
1import { ArrayParam, useQueryParam, useQueryParams } from 'use-query-params'; 2 3// typically used with the hooks: 4const [foo, setFoo] = useQueryParam('foo', ArrayParam); 5// - OR - 6const [query, setQuery] = useQueryParams({ foo: ArrayParam });
Example with Custom Param
You can define your own params if the ones shipped with this package don't work for you. There are included serialization utility functions to make this easier, but you can use whatever you like.
1import { 2 encodeDelimitedArray, 3 decodeDelimitedArray 4} from 'use-query-params'; 5 6/** Uses a comma to delimit entries. e.g. ['a', 'b'] => qp?=a,b */ 7const CommaArrayParam = { 8 encode: (array: string[] | null | undefined) => 9 encodeDelimitedArray(array, ','), 10 11 decode: (arrayStr: string | string[] | null | undefined) => 12 decodeDelimitedArray(arrayStr, ',') 13};
1useQueryParam<T>(name: string, paramConfig?: QueryParamConfig<T>, options?: QueryParamOptions): 2 [T | undefined, (newValue: T, updateType?: UrlUpdateType) => void]
Given a query param name and query parameter configuration { encode, decode }
return the decoded value and a setter for updating it. If you do not provide a paramConfig, it inherits it from what was defined in the QueryParamProvider, falling back to StringParam if nothing is found.
The setter takes two arguments (newValue, updateType)
where updateType
is one of 'pushIn' | 'push' | 'replaceIn' | 'replace'
, defaulting to
'pushIn'
.
You can override options from the QueryParamProvider with the third argument. See QueryParamOptions for details.
Example
1import { useQueryParam, NumberParam } from 'use-query-params'; 2 3// reads query parameter `foo` from the URL and stores its decoded numeric value 4const [foo, setFoo] = useQueryParam('foo', NumberParam); 5setFoo(500); 6setFoo(123, 'push'); 7 8// to unset or remove a parameter set it to undefined and use pushIn or replaceIn update types 9setFoo(undefined) // ?foo=123&bar=zzz becomes ?bar=zzz 10 11// functional updates are also supported: 12setFoo((latestFoo) => latestFoo + 150)
1// option 1: pass only a config with possibly some options 2useQueryParams<QPCMap extends QueryParamConfigMapWithInherit>( 3 paramConfigMap: QPCMap, 4 options?: QueryParamOptions 5): [DecodedValueMap<QPCMap>, SetQuery<QPCMap>]; 6 7// option 2: pass an array of param names, relying on predefined params for types 8useQueryParams<QPCMap extends QueryParamConfigMapWithInherit>( 9 names: string[], 10 options?: QueryParamOptions 11): [DecodedValueMap<QPCMap>, SetQuery<QPCMap>]; 12 13// option 3: pass no args, get all params back that were predefined in a proivder 14useQueryParams<QPCMap extends QueryParamConfigMapWithInherit>( 15): [DecodedValueMap<QPCMap>, SetQuery<QPCMap>];
Given a query parameter configuration (mapping query param name to { encode, decode }
),
return an object with the decoded values and a setter for updating them.
The setter takes two arguments (newQuery, updateType)
where updateType
is one of 'pushIn' | 'push' | 'replaceIn' | 'replace'
, defaulting to
'pushIn'
.
You can override options from the QueryParamProvider with the options argument. See QueryParamOptions for details.
Example
1import { useQueryParams, StringParam, NumberParam } from 'use-query-params'; 2 3// reads query parameters `foo` and `bar` from the URL and stores their decoded values 4const [query, setQuery] = useQueryParams({ foo: NumberParam, bar: StringParam }); 5setQuery({ foo: 500 }) 6setQuery({ foo: 123, bar: 'zzz' }, 'push'); 7 8// to unset or remove a parameter set it to undefined and use pushIn or replaceIn update types 9setQuery({ foo: undefined }) // ?foo=123&bar=zzz becomes ?bar=zzz 10 11// functional updates are also supported: 12setQuery((latestQuery) => ({ foo: latestQuery.foo + 150 }))
Example with Custom Parameter Type
Parameter types are just objects with { encode, decode }
functions. You can
provide your own if the provided ones don't work for your use case.
1import { useQueryParams } from 'use-query-params'; 2 3const MyParam = { 4 encode(value) { 5 return `${value * 10000}`; 6 }, 7 8 decode(strValue) { 9 return parseFloat(strValue) / 10000; 10 } 11} 12 13// ?foo=10000 -> query = { foo: 1 } 14const [query, setQuery] = useQueryParams({ foo: MyParam }); 15 16// goes to ?foo=99000 17setQuery({ foo: 99 })
1withQueryParams<QPCMap extends QueryParamConfigMap, P extends InjectedQueryProps<QPCMap>> 2 (paramConfigMap: QPCMap, WrappedComponent: React.ComponentType<P>): 3 React.FC<Diff<P, InjectedQueryProps<QPCMap>>>
Given a query parameter configuration (mapping query param name to { encode, decode }
) and
a component, inject the props query
and setQuery
into the component based on the config.
The setter takes two arguments (newQuery, updateType)
where updateType
is one of 'pushIn' | 'push' | 'replaceIn' | 'replace'
, defaulting to
'pushIn'
.
Example
1import { withQueryParams, StringParam, NumberParam } from 'use-query-params'; 2 3const MyComponent = ({ query, setQuery, ...others }) => { 4 const { foo, bar } = query; 5 return <div>foo = {foo}, bar = {bar}</div> 6} 7 8// reads query parameters `foo` and `bar` from the URL and stores their decoded values 9export default withQueryParams({ foo: NumberParam, bar: StringParam }, MyComponent);
Note there is also a variant called withQueryParamsMapped
that allows you to do a react-redux style mapStateToProps equivalent. See the code or this example for details.
1<QueryParams config={{ foo: NumberParam }}> 2 {({ query, setQuery }) => <div>foo = {query.foo}</div>} 3</QueryParams>
Given a query parameter configuration (mapping query param name to { encode, decode }
) and
a component, provide render props query
and setQuery
based on the config.
The setter takes two arguments (newQuery, updateType)
where updateType
is one of 'pushIn' | 'push' | 'replaceIn' | 'replace'
, defaulting to
'pushIn'
.
1encodeQueryParams<QPCMap extends QueryParamConfigMap>( 2 paramConfigMap: QPCMap, 3 query: Partial<DecodedValueMap<QPCMap>> 4): EncodedQueryWithNulls
Convert the values in query to strings via the encode functions configured in paramConfigMap. This can be useful for constructing links using decoded query parameters.
Example
1import { encodeQueryParams, NumberParam } from 'use-query-params'; 2// since v1.0 stringify is not exported from 'use-query-params', 3// so you must install the 'query-string' package in case you need it 4import { stringify } from 'query-string'; 5 6// encode each parameter according to the configuration 7const encodedQuery = encodeQueryParams({ foo: NumberParam }, { foo }); 8const link = `/?${stringify(encodedQuery)}`;
1// choose an adapter, depending on your router 2import { ReactRouter6Adapter } from 'use-query-params/adapters/react-router-6'; 3import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5'; 4<QueryParamProvider adapter={ReactRouter6Adapter}><App /></QueryParamProvider> 5 6// optionally specify options 7import { parse, stringify } from 'query-string'; 8const options = { 9 searchStringToObject: parse, 10 objectToSearchString: stringify, 11} 12<QueryParamProvider adapter={ReactRouter6Adapter} options={options}> 13 <App /> 14</QueryParamProvider> 15 16// optionally nest parameters in options to get automatically on useQueryParams calls 17<QueryParamProvider adapter={ReactRouter6Adapter} options={{ 18 params: { foo: NumberParam } 19}}> 20 <App> {/* useQueryParams calls have access to foo here */} 21 ... 22 <Page1> 23 <QueryParamProvider options={{ params: { bar: BooleanParam }}}> 24 ... {/* useQueryParams calls have access to foo and bar here */} 25 </QueryParamProvider> 26 </Page1> 27 ... 28 </App> 29</QueryParamProvider>
The QueryParamProvider component links your routing library's history to the useQueryParams hook. It is needed for the hook to be able to update the URL and have the rest of your app know about it.
You can specify global options at the provider level.
option | default | description |
---|---|---|
updateType | "pushIn" | How the URL gets updated by default, one of: replace, replaceIn, push, pushIn. |
searchStringToObject | from serialize-query-params | How to convert the search string e.g. ?foo=123&bar=x into an object. Default uses URLSearchParams, but you could also use parse from query-string for example. `(searchString: string) => Record<string, string |
objectToSearchString | from serialize-query-params | How to convert an object (e.g. { foo: 'x' } -> foo=x into a search string – no "?" included). Default uses URLSearchParams, but you could also use stringify from query-string for example. `(query: Record<string, string |
params | undefined | Define parameters at the provider level to be automatically available to hook calls. Type is QueryParamConfigMap, e.g. { params: { foo: NumberParam, bar: BooleanParam }} |
includeKnownParams | undefined | When true, include all parameters that were configured via the params option on a QueryParamProvider. Default behavior depends on the arguments passed to useQueryParams (if not specifying any params, it is true, otherwise false). |
includeAllParams | false | Include all parameters found in the URL even if not configured in any param config. |
removeDefaultsFromUrl | false | When true, removes parameters from the URL when set is called if their value is the same as their default (based on the default attribute of the Param object, typically populated by withDefault() ) |
enableBatching | false | experimental - turns on batching (i.e., multiple consecutive calls to setQueryParams in a row only result in a single update to the URL). Currently marked as experimental since we need to update all the tests to verify no issues occur, feedback welcome. |
Run the typescript compiler in watch mode:
npm run dev
You can run an example app:
npm link
cd examples/react-router
npm install
npm link use-query-params
npm start
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 7/30 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
27 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More