Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Last active August 15, 2023 21:03
Show Gist options
  • Save tomsoderlund/c352b561df7de0330ec3b36dcc26fe5b to your computer and use it in GitHub Desktop.
Save tomsoderlund/c352b561df7de0330ec3b36dcc26fe5b to your computer and use it in GitHub Desktop.
Like useState hook, but saves current state in browser search bar (Next.js router query)
// import useRouterQueryState from '../hooks/useRouterQueryState'
// const [myState, setMyState] = useRouterQueryState(propertyName, defaultValue)
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
function useRouterQueryState (key, defaultValue) {
const router = useRouter()
// Get initial state from router query or default value
const [state, setState] = useState(router.query[key] ?? defaultValue)
useEffect(() => {
// Update state when router query changes
setState(router.query[key] || '')
// Also, set up an event listener for route changes
const handleRouteChange = (url) => {
setState(router.query[key] || '')
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.query])
const setQueryState = (value) => {
setState(value)
// Update the URL without navigating
const queryWithoutKey = { ...router.query }
delete queryWithoutKey[key]
router.push({
pathname: router.pathname,
query: {
...queryWithoutKey,
...(value && { [key]: value })
}
}, undefined, { shallow: true })
}
return [state, setQueryState]
}
export default useRouterQueryState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment