use-tab-searchparams.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { usePathname, useRouter, useSearchParams } from 'next/navigation'
  2. type UseTabSearchParamsOptions = {
  3. defaultTab: string
  4. routingBehavior?: 'push' | 'replace'
  5. searchParamName?: string
  6. }
  7. /**
  8. * Custom hook to manage tab state via URL search parameters in a Next.js application.
  9. * This hook allows for syncing the active tab with the browser's URL, enabling bookmarking and sharing of URLs with a specific tab activated.
  10. *
  11. * @param {UseTabSearchParamsOptions} options Configuration options for the hook:
  12. * - `defaultTab`: The tab to default to when no tab is specified in the URL.
  13. * - `routingBehavior`: Optional. Determines how changes to the active tab update the browser's history ('push' or 'replace'). Default is 'push'.
  14. * - `searchParamName`: Optional. The name of the search parameter that holds the tab state in the URL. Default is 'category'.
  15. * @returns A tuple where the first element is the active tab and the second element is a function to set the active tab.
  16. */
  17. export const useTabSearchParams = ({
  18. defaultTab,
  19. routingBehavior = 'push',
  20. searchParamName = 'category',
  21. }: UseTabSearchParamsOptions) => {
  22. const router = useRouter()
  23. const pathName = usePathname()
  24. const searchParams = useSearchParams()
  25. const activeTab = searchParams.get(searchParamName) || defaultTab
  26. const setActiveTab = (newActiveTab: string) => {
  27. router[routingBehavior](`${pathName}?${searchParamName}=${newActiveTab}`)
  28. }
  29. return [activeTab, setActiveTab] as const
  30. }