Skip to content

How to change the page favicon based on the result of an operation ​

This example demonstrates how to change the page favicon based on the result of an operation using the useFavicon hook.

Watch the live preview.

tsx
import {useFavicon} from './useFavicon';

const successFavicon = 'successFavicon.ico';
const errorFavicon = 'errorFavicon.ico';

export default function App() {
    const {faviconUrl, changeFavicon} = useFavicon();

    const onRunOperation = () => {
        if (Math.random() > 0.5) {
            changeFavicon(successFavicon);
        } else {
            changeFavicon(errorFavicon);
        }
    };

    return (
        <>
            <button onClick={onRunOperation}>Run operation</button>
            <p>Status: {faviconUrl === successFavicon ? 'Success' : 'Error'}</p>
        </>
    );
};
typescript
import {useState} from 'react';

export const useFavicon = () => {
    const [faviconUrl, setFaviconUrl] = useState(
        (document.querySelector(`link[rel~="icon"]`) as HTMLLinkElement)?.href
    );

    const changeFavicon = (newFavicon: string) => {
        let link = document.querySelector(`link[rel~="icon"]`) as HTMLLinkElement;

        if (!link) {
            link = document.createElement('link');
            link.rel = 'icon';
            document.head.appendChild(link);
        }

        link.href = newFavicon;
        setFaviconUrl(newFavicon);
    };

    return {faviconUrl, changeFavicon};
};