diff --git a/snippets/useTitle.md b/snippets/useTitle.md new file mode 100644 index 000000000..4d5cd32c5 --- /dev/null +++ b/snippets/useTitle.md @@ -0,0 +1,48 @@ +--- +title: useTitle +tags: hooks,effect,intermediate +firstSeen: 2021-09-27T05:00:00-04:00 +--- + +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. + +```jsx +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; + }; + }, []); +}; +``` + +```jsx +const Alert = () => { + useTitle('Alert'); + return
Alert! Title has changed
; +}; + +const MyApp = () => { + const [alertOpen, setAlertOpen] = React.useState(false); + + return ( + <> + + {alertOpen &&