Menu

gitpiper

useTitle react Code Snippet in 2024

hookseffectintermediate

Last Updated: 21 March 2024

Sets the title of the page

  • Use typeof to determine if the document is defined or not.
  • Use the useRef() hook to store the original title of the document, if defined.
  • Use the useEffect() hook to set Document.title to the passed value when the component mounts and clean up when unmounting.
const useTitle = title => { const documentDefined = typeof document !== 'undefined'; const originalTitle = React.useRef(documentDefined ? document.title : null); React.useEffect(() => { if (!documentDefined) return; if (document.title !== title) document.title = title; return () => { document.title = originalTitle.current; }; }, []); };
const Alert = () => { useTitle('Alert'); return <p>Alert! Title has changed</p>; }; const MyApp = () => { const [alertOpen, setAlertOpen] = React.useState(false); return ( <> <button onClick={() => setAlertOpen(!alertOpen)}>Toggle alert</button> {alertOpen && <Alert />} </> ); }; ReactDOM.render(<MyApp />, document.getElementById('root'));

react snippet similar to useTitle For You in March 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️