How to Create a Custom React Hook: useSetWindowTitle
In the world of React, custom hooks have become an essential tool for writing clean, reusable, and modular logic. They allow developers to extract repeated behavior into a simple function, enhancing both readability and maintainability.
One interesting use case is managing the browser window title (i.e., document.title
). Imagine you want to dynamically set the page’s title based on user navigation, data fetching, or any specific action. Instead of cluttering your components with repetitive useEffect
calls, you can encapsulate this logic into a custom hook. Let’s call it useSetWindowTitle
.
What is useSetWindowTitle
?
useSetWindowTitle
is a custom React hook that serves as a wrapper for useEffect
, designed to update the browser’s window title dynamically. It simplifies what would otherwise be boilerplate code in every component.
✨ Key Features
- Encapsulation of logic: Handles title updates in one place.
- Reusability: Import and use in any component with a single call.
- Clean code: Keeps components focused on UI rather than browser behaviors.
- Restores original title (optional): Ensures a component can clean up after itself.
🛠️ How to Build useSetWindowTitle
Here’s a complete implementation of useSetWindowTitle
:
import { useEffect } from 'react';
function useSetWindowTitle(title) {
useEffect(() => {
// Save the original title
const originalTitle = document.title;
// Update the window title
document.title = title;
// Cleanup: Restore original title when component unmounts
return () => {
document.title = originalTitle;
};
}, [title]); // Run effect when 'title' changes
}
export default useSetWindowTitle;
This function:
- Takes a
title
parameter representing the new window title. - Saves the original title so it can be restored later.
- Updates
document.title
whenever thetitle
argument changes. - Cleans up on unmount, restoring the previous title to avoid unexpected changes.
🚀 How to Use It
Here’s an example of how you might use useSetWindowTitle
in a React component:
import React from 'react';
import useSetWindowTitle from './useSetWindowTitle';
function ProfilePage() {
useSetWindowTitle("User Profile");
return <h1>Welcome to your profile!</h1>;
}
export default ProfilePage;
Every time ProfilePage
is mounted, the window title changes to "User Profile". When you navigate away, the previous title is restored.
🔎 Why Use a Custom Hook for This?
You might wonder: "Why not just put useEffect
directly in the component?" While that works, custom hooks offer several advantages:
- DRY Principle: Avoid repeating the same logic across multiple components.
- Testability: It’s easier to test a hook’s logic in isolation.
- Organization: Keeps components focused on rendering and user interaction.
- Scalability: When multiple components need the same behavior, simply call the hook.
⚠️ Things to Consider
- Always use the
use
prefix for custom hooks to let React recognize them as hooks. - Follow the rules of hooks: Only call hooks at the top level of your components, not inside loops or conditionals.
- Dependency management: If you plan to depend on multiple variables to control the title, you can expand the hook’s dependency array.
- SEO implications: Remember that
document.title
is a client-side change. Search engines don’t necessarily see it if they don’t render JavaScript. - React Router integration: You can combine this with React Router to set titles based on routes.
📝 Finally
The useSetWindowTitle
hook is a simple yet powerful example of how custom hooks can clean up repetitive logic, enhance readability, and improve maintainability. Whether you’re working on a small side project or a large-scale application, this approach can save you time and reduce errors.
If you haven’t embraced custom hooks yet, this might be the perfect reason to start.
Comments ()