Create a useTitle Hook in React
This challenge asks you to build a custom React hook, useTitle, that dynamically updates the document title based on a provided string. This is a common requirement in React applications to provide users with clear context about the current page or view, improving user experience and SEO. The hook should accept a title string as input and update the document's title accordingly.
Problem Description
You need to create a reusable React hook called useTitle that accepts a single argument: a title string. This hook should update the document's title to the provided title whenever the title prop changes. The hook should handle initial title setting and subsequent updates.
Key Requirements:
- The hook must accept a
titlestring as an argument. - The hook must update the document's title using
document.title. - The hook should handle the initial title setting when it's first called.
- The hook should re-render the component when the
titleprop changes, ensuring the title is updated.
Expected Behavior:
When the useTitle hook is called with a title string, the document's title should be immediately updated to that string. If the title string changes, the document's title should be updated again. If the hook is unmounted, no errors should occur.
Edge Cases to Consider:
- Empty or null
titlestring: Should the title be cleared or remain unchanged? (Assume clearing is preferred for this challenge). - Rapid title changes: The hook should handle frequent updates without causing performance issues.
- Unmounting the component: The hook should not cause errors when the component unmounts.
Examples
Example 1:
Input: title = "My Awesome App"
Output: document.title = "My Awesome App"
Explanation: The hook sets the document title to "My Awesome App" upon initial render.
Example 2:
Input: title = "My Awesome App", then title = "New Title"
Output: document.title = "New Title"
Explanation: The hook updates the document title to "New Title" when the title prop changes.
Example 3: (Edge Case)
Input: title = ""
Output: document.title = ""
Explanation: The hook clears the document title when an empty string is provided.
Constraints
- The hook must be written in TypeScript.
- The hook should be a functional hook (using
useStateis not required, but acceptable if you feel it improves clarity). - The hook should not introduce any unnecessary dependencies.
- The hook should be performant and avoid unnecessary re-renders.
- The hook should not modify any external state other than
document.title.
Notes
- Consider using
useEffectto manage the side effect of updating the document title. - Think about how to handle the initial title setting and subsequent updates efficiently.
- Focus on creating a clean, reusable, and well-typed hook.
- The goal is to create a simple and effective hook that updates the document title based on a provided string.