Jordi Enric

Software Engineer at Supabase logoSupabase

Back

May 3, 2024

use-router-tabs.ts

When I use the `<Tab>` component from shadcn UI many times I want to sync that state of the tab with the URL so that users can deeplink to the tab or use the browser back/forth functions.

I made a simple hook that I call when I want to achieve this, looks like this:

import { useRouter } from "next/router";

export function useRouterTabs(name = "tab") {
  const router = useRouter();

  return {
    tabValue: router.query.tab as string,
    onTabChange: (tab: string) => {
      router.push({
        query: {
          ...router.query,
          [name]: tab,
        },
      });
    },
  };
}

And in use it looks like this:

  const { tabValue, onTabChange } = useRouterTabs("tab");

  <Tabs
    value={tabValue}
    onValueChange={(tabVal) => {
      onTabChange(tabVal);
    }}
  >
  ...
</Tabs>

And it works:

Back to all posts