vitess.io/vitess@v0.16.2/web/vtadmin/src/hooks/useDocumentTitle.ts (about)

     1  import { useEffect } from 'react';
     2  import { env } from '../util/env';
     3  
     4  const BASE_TITLE = env().REACT_APP_DOCUMENT_TITLE || 'VTAdmin';
     5  
     6  // useDocumentTitle is a simple hook to set the document.title of the page.
     7  //
     8  // Note that there's a noticeable delay, around ~500ms, between
     9  // when the parent component renders and when the document.title
    10  // is updated. It's not terrible... but it is a little bit annoying.
    11  //
    12  // Unfortunately, neither React hooks nor react-router offer
    13  // a mechanism to hook into the "componentWillMount" stage before the
    14  // first render. This problem seems to be common even in libraries
    15  // like react-helmet; see https://github.com/nfl/react-helmet/issues/189.
    16  //
    17  // Other approaches that still, unfortunately, exhibit the lag:
    18  //
    19  //  - Setting document.title directly in component functions
    20  //  - Setting document.title in a Route component's render prop
    21  //  - Setting document.title on history.listen events
    22  //
    23  export const useDocumentTitle = (title: string) => {
    24      // Update document.title whenever the `title` argument changes.
    25      useEffect(() => {
    26          document.title = `${title} | ${BASE_TITLE}`;
    27      }, [title]);
    28  
    29      // Restore the default document title on unmount.
    30      // (While one may think this might be the source of the aforementioned delay
    31      // (and that idea wouldn't be far off since this indeed double-updates the title)
    32      // that is not the case as the lag happens even without this.)
    33      useEffect(() => {
    34          return () => {
    35              document.title = BASE_TITLE;
    36          };
    37      }, []);
    38  };