@react-hookz/web
Version:
React hooks done right, for browser and SSR.
25 lines (24 loc) • 950 B
JavaScript
import { useEffect, useRef } from 'react';
import { isBrowser } from "../util/const.js";
import { useUnmountEffect, useSyncedRef } from '..';
/**
* Sets title of the page.
*
* @param title Title to set, if wrapper option is set, it will be passed through wrapper function.
* @param options Options object.
*/
export function useDocumentTitle(title, options) {
if (options === void 0) { options = {}; }
var titleRef = useRef(isBrowser ? document.title : '');
var optionsRef = useSyncedRef(options);
// it is safe not to check isBrowser here, as effects are not invoked in SSR
useEffect(function () {
document.title = options.wrapper ? options.wrapper(title) : title;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [title, options.wrapper]);
useUnmountEffect(function () {
if (optionsRef.current.restoreOnUnmount) {
document.title = titleRef.current;
}
});
}