React hook for sharing state via URL.
$ npm install @Kikobeats/use-query-state --save
Just get it from window.location.search
const [query, setQuery] = useQueryState()
This is especially useful for Server-side Rendering (SSR), when the initial query state will depends on the incoming request.
const [query, setQuery] = useQueryState(ssrQuery)
Sometimes you want to modify the window.location.search
for anything you need for.
const safeDecode = value => {
try {
return decodeURIComponent(value)
} catch (_) {
return value
}
}
const [query, setQuery] = useQueryState(undefined, parsedQuery =>
Object.entries(parsedQuery).reduce((acc, [key, value]) => {
acc[key] = safeDecode(value)
return acc
}, {})
)
Gatsby uses navigate
instead of window.history.pushState
, so you you need to load @kikobeats/use-query-state/gatsby
instead.
use-query-state © Kiko Beats, released under the MIT License.
Authored and maintained by Kiko Beats with help from contributors.
kikobeats.com · GitHub Kiko Beats · Twitter @Kikobeats