UIBeginnerSSR-safehooks/ui/useTabs.ts

useTabs

Tab value + a11y prop getters.

Import

TypeScript
import { useTabs } from '@/hooks';

API

Signature

useTabs({ defaultValue }) → { value, getTabProps, getPanelProps }

When to use

Use useTabs instead of re-implementing the same pattern in multiple components.

SSR / Next.js

DOM extras (scroll lock, focus trap) run only in effects.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useTabs
Editor
function SettingsTabs() {
  const tabs = useTabs({ defaultValue: 'general' });
  return (
    <div>
      <button {...tabs.getTabProps('general')}>General</button>
      <button {...tabs.getTabProps('billing')}>Billing</button>
      <div {...tabs.getPanelProps('general')}>General panel</div>
      <div {...tabs.getPanelProps('billing')}>Billing panel</div>
    </div>
  );
}
Preview

Implementation source

Full library source for useTabs — copy into your project when you are not installing a package yet.

hooks/ui/useTabs.ts
import { useCallback, useState } from 'react';

export interface UseTabsOptions {
  defaultValue: string;
  onChange?: (value: string) => void;
}

/** Tab selection state. */
export function useTabs(options: UseTabsOptions) {
  const { defaultValue, onChange } = options;
  const [value, setValueRaw] = useState(defaultValue);

  const setValue = useCallback(
    (next: string) => {
      setValueRaw(next);
      onChange?.(next);
    },
    [onChange],
  );

  const getTabProps = useCallback(
    (id: string) => ({
      role: 'tab' as const,
      'aria-selected': value === id,
      onClick: () => setValue(id),
    }),
    [value, setValue],
  );

  const getPanelProps = useCallback(
    (id: string) => ({
      role: 'tabpanel' as const,
      hidden: value !== id,
    }),
    [value],
  );

  return { value, setValue, getTabProps, getPanelProps };
}

Copy-paste example

useTabs.example.tsx
'use client';

import { useTabs } from '@/hooks';

export function SettingsTabs() {
  const tabs = useTabs({ defaultValue: 'general' });
  return (
    <div>
      <button {...tabs.getTabProps('general')}>General</button>
      <button {...tabs.getTabProps('billing')}>Billing</button>
      <div {...tabs.getPanelProps('general')}>General panel</div>
      <div {...tabs.getPanelProps('billing')}>Billing panel</div>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: These are headless — you own the markup and styles.
  • Source of truth: open hooks/ui/useTabs.ts for implementation details