useFavicon

React hook to change the page favicon.

Add the hook via the CLI:

npx @novajslabs/cli add useFavicon

Or copy and paste the code into your project:

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
}

React 16.8 or higher

  • Name
    changeFavicon
    Type
    function
    Description

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

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

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