Custom Hooks: Creating a Dynamic Page Title

Custom Hooks: Creating a Dynamic Page Title

Harnessing the Power of useTitle in React

Custom hooks are regular JavaScript functions that follow specific naming conventions.

When you have certain logic or some chunk of code that is to be applied on every page or multiple pages, you could just create a custom hook. Define it once and call it wherever you need to implement it.

How to build one from scratch? You need to follow a certain naming convention that is prefixed with 'use' at the beginning. It is not mandatory to follow up on the naming convention because it is not enforced by REACT.

Our REACT community prefers the naming convention and it improves code readability and maintains consistency.

Let's create the most used custom hook in most of the projects. You could add every custom hook in a folder called 'hooks' (totally optional)

import { useEffect } from "react";

export const useTitle = (title) => {
    useEffect( ()=>{
        document.title = `${title} | bRAND nAME`;
    },[title] );

return null;
}

Let me explain the above code, I am using a hook provided by React, useEffect() - which accepts a function and dependency. Why? because of DOM manipulation, every time the title will change the above code would run. To use our custom hook you need to import it let me demonstrate,

// example your Home Component

import { useTitle } from './path';

export const Home = () => {
useTitle("Home");

return(<> ... some JSX </>)
}

That is how you create and use the custom hook - useTitle(). Thank you for your time!