UIBeginnerSSR-safehooks/ui/useTooltip.ts

useTooltip

Delayed show/hide tooltip state.

Import

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

API

Signature

useTooltip(options?) → { isOpen, getTriggerProps, ... }

When to use

Use useTooltip 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 · useTooltip
Editor
function Hint() {
  const tip = useTooltip({ delayShow: 200, delayHide: 100 });
  return (
    <button {...tip.getTriggerProps()}>
      Hover me
      {tip.isOpen && <span role="tooltip">Helpful text</span>}
    </button>
  );
}
Preview

Implementation source

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

hooks/ui/useTooltip.ts
import { useCallback, useRef, useState } from 'react';
import { useTimeoutFn } from '../timer/useTimeoutFn';

export interface UseTooltipOptions {
  delayShow?: number;
  delayHide?: number;
  defaultOpen?: boolean;
}

/** Tooltip visibility with open/hide delays. */
export function useTooltip(options: UseTooltipOptions = {}) {
  const { delayShow = 200, delayHide = 0, defaultOpen = false } = options;
  const [isOpen, setIsOpen] = useState(defaultOpen);
  const pending = useRef<'show' | 'hide' | null>(null);

  const showTimer = useTimeoutFn(() => {
    setIsOpen(true);
    pending.current = null;
  }, delayShow);

  const hideTimer = useTimeoutFn(() => {
    setIsOpen(false);
    pending.current = null;
  }, delayHide);

  const open = useCallback(() => {
    hideTimer.clear();
    pending.current = 'show';
    if (delayShow <= 0) {
      setIsOpen(true);
      return;
    }
    showTimer.start();
  }, [delayShow, showTimer, hideTimer]);

  const close = useCallback(() => {
    showTimer.clear();
    pending.current = 'hide';
    if (delayHide <= 0) {
      setIsOpen(false);
      return;
    }
    hideTimer.start();
  }, [delayHide, showTimer, hideTimer]);

  const getTriggerProps = useCallback(
    () => ({
      onMouseEnter: open,
      onMouseLeave: close,
      onFocus: open,
      onBlur: close,
    }),
    [open, close],
  );

  return { isOpen, open, close, getTriggerProps };
}

Copy-paste example

useTooltip.example.tsx
'use client';

import { useTooltip } from '@/hooks';

export function Hint() {
  const tip = useTooltip({ delayShow: 200, delayHide: 100 });
  return (
    <button {...tip.getTriggerProps()}>
      Hover me
      {tip.isOpen && <span role="tooltip">Helpful text</span>}
    </button>
  );
}

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/useTooltip.ts for implementation details