Skip to content

useFavicon

React hook to change the page favicon.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useFavicon
sh
npx @novajslabs/cli add useFavicon
sh
pnpm dlx @novajslabs/cli add useFavicon

Or copy and paste the code into your project:

ts
import { useEffect, useState } from "react";

export const useFavicon = (): ((newFavicon: string) => void) => {
  const [faviconUrl, setFaviconUrl] = useState<string>("");

  useEffect(() => {
    let link = document.querySelector(`link[rel~="icon"]`) as HTMLLinkElement;

    if (!link) {
      link = document.createElement("link");
      link.type = "image/x-icon";
      link.rel = "icon";
      document.head.appendChild(link);
    }

    link.href = faviconUrl;
  }, [faviconUrl]);

  const changeFavicon = (newFavicon: string) => setFaviconUrl(newFavicon);

  return changeFavicon;
};
js
import { useEffect, useState } from "react";

export const useFavicon = () => {
  const [faviconUrl, setFaviconUrl] = useState("");

  useEffect(() => {
    let link = document.querySelector(`link[rel~="icon"]`);

    if (!link) {
      link = document.createElement("link");
      link.type = "image/x-icon";
      link.rel = "icon";
      document.head.appendChild(link);
    }

    link.href = faviconUrl;
  }, [faviconUrl]);

  const changeFavicon = (newFavicon) => setFaviconUrl(newFavicon);

  return changeFavicon;
};

Requirements

React 16.8 or higher

Return values

changeFavicon

Type: function

Set the page favicon. This function accepts the new favicon.

Example

tsx
import { useFavicon } from "./hooks/useFavicon";
import successFav from "./success.ico";
import errorFav from "./error.ico";

const App = () => {
  const changeFavicon = useFavicon();

  const generateNumber = () => {
    const randomNumber = Math.floor(Math.random() * 10) + 1;

    if (randomNumber <= 5) {
      changeFavicon(successFav);
    } else {
      changeFavicon(errorFav);
    }
  };

  return <button onClick={generateNumber}>Generate number</button>;
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Dynamically updating the favicon based on real-time notifications in a web-based messaging application
  • Changing the favicon to indicate different states (e.g., online, offline) in a web-based status tracking tool
  • Updating the favicon to reflect the current weather conditions in a weather forecast web application

Released under the MIT License.