Write a useDocumentTitle hook that puts the old title back on unmount
Write useDocumentTitle(title). While the component that calls it is on the page, the browser tab shows title, and it follows title when it changes. When the component goes, the tab shows the title it had before the hook set its own.
It must work when a second component with its own title appears later, like a checkout dialog over a cart page: closing the dialog puts the cart's title back. It must also work in Strict Mode.
function CartPage({ count }) {
useDocumentTitle("Cart (" + count + ")");
return <h1>Your cart</h1>;
}
import { useEffect } from "react";
export function useDocumentTitle(title) {
// Show title in the browser tab while the component is on the page,
// and put the earlier title back when it leaves.
}
- shows the title while the component is on the page
- puts the old title back on unmount
- follows the title when it changes
- after the title changed, unmounting puts back the title from before the hook
- closing a dialog with its own title puts the page's title back
- works in Strict Mode
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…