Skip to content

Commit b8b3e47

Browse files
authored
feat: add option to useTitle to restore title on un-mount
2 parents 75835cb + 8faa71f commit b8b3e47

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

src/useTitle.ts

+19-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
1-
import { useRef } from 'react';
2-
3-
function useTitle(title: string) {
4-
const t = useRef<string>();
5-
6-
if (t.current !== title) {
7-
document.title = t.current = title;
8-
}
1+
import { useRef, useEffect } from 'react';
2+
export interface UseTitleOptions {
3+
restoreOnUnmount?: boolean;
4+
}
5+
const DEFAULT_USE_TITLE_OPTIONS: UseTitleOptions = {
6+
restoreOnUnmount: false,
7+
};
8+
function useTitle(title: string, options: UseTitleOptions = DEFAULT_USE_TITLE_OPTIONS) {
9+
const prevTitleRef = useRef(document.title);
10+
document.title = title;
11+
useEffect(() => {
12+
if (options && options.restoreOnUnmount) {
13+
return () => {
14+
document.title = prevTitleRef.current;
15+
};
16+
} else {
17+
return;
18+
}
19+
}, []);
920
}
1021

1122
export default typeof document !== 'undefined' ? useTitle : (_title: string) => {};

tests/useTitle.test.tsx renamed to tests/useTitle.test.ts

+12
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,16 @@ describe('useTitle', () => {
1313
hook.rerender('My other page title');
1414
expect(document.title).toBe('My other page title');
1515
});
16+
17+
it('should restore document title on unmount', () => {
18+
renderHook(props => useTitle(props), { initialProps: 'Old Title' });
19+
expect(document.title).toBe('Old Title');
20+
21+
const hook = renderHook(props => useTitle(props.title, { restoreOnUnmount: props.restore }), {
22+
initialProps: { title: 'New Title', restore: true },
23+
});
24+
expect(document.title).toBe('New Title');
25+
hook.unmount();
26+
expect(document.title).toBe('Old Title');
27+
});
1628
});

0 commit comments

Comments
 (0)