All files / hooks/use-document-title/src useDocumentTitle.ts

91.66% Statements 11/12
90.9% Branches 10/11
100% Functions 4/4
91.66% Lines 11/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                                            7x     7x   7x 7x     7x 5x   7x     7x 5x 5x         2x              
import { useEffect, useRef } from "react";
 
/**
 * Options for the useDocumentTitle hook.
 */
export interface UseDocumentTitleOptions {
  /**
   * Restore the title that was present when the component mounted when it
   * unmounts.
   * @default false
   */
  restoreOnUnmount?: boolean;
}
 
/**
 * Sets `document.title` to the given value, keeping it in sync as `title`
 * changes. Optionally restores the original title on unmount.
 *
 * SSR-safe: does nothing when `document` is unavailable.
 *
 * @param title - The title to set
 * @param options - Configuration (`restoreOnUnmount`)
 *
 * @example
 * ```tsx
 * useDocumentTitle(`Inbox (${unread})`);
 * ```
 *
 * @example
 * ```tsx
 * // Restore the previous title when this screen unmounts
 * useDocumentTitle("Checkout", { restoreOnUnmount: true });
 * ```
 */
export function useDocumentTitle(
  title: string,
  options: UseDocumentTitleOptions = {}
): void {
  const { restoreOnUnmount = false } = options;
 
  // Capture the title present at mount, once, so it can be restored later.
  const originalTitleRef = useRef<string | null>(null);
 
  useEffect(() => {
    Iif (typeof document === "undefined") {
      return;
    }
    if (originalTitleRef.current === null) {
      originalTitleRef.current = document.title;
    }
    document.title = title;
  }, [title]);
 
  useEffect(() => {
    return () => {
      if (
        restoreOnUnmount &&
        typeof document !== "undefined" &&
        originalTitleRef.current !== null
      ) {
        document.title = originalTitleRef.current;
      }
    };
    // Restore behavior is fixed at mount; intentionally not reacting to changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}