useFavicon
Update the favicon href.
Import
TypeScript
import { useFavicon } from '@/hooks';API
Signature
useFavicon(href)
When to use
Use useFavicon instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Browser utilities are SSR-gated; lifecycle hooks are safe.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useFaviconEditor
function StatusFavicon({ ok }: { ok: boolean }) { useFavicon(ok ? '/favicon-ok.ico' : '/favicon-err.ico'); return null; }
Preview
Implementation source
Full library source for useFavicon — copy into your project when you are not installing a package yet.
hooks/utility/useFavicon.ts
import { useEffect } from 'react';
import { isBrowser } from './isBrowser';
/** Updates the page favicon href. */
export function useFavicon(href: string): void {
useEffect(() => {
if (!isBrowser() || !href) return;
let link = document.querySelector<HTMLLinkElement>("link[rel*='icon']");
const created = !link;
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
const previous = link.href;
link.href = href;
return () => {
if (created && link) {
link.remove();
} else if (link) {
link.href = previous;
}
};
}, [href]);
}
Copy-paste example
useFavicon.example.tsx
'use client';
import { useFavicon } from '@/hooks';
export function StatusFavicon({ ok }: { ok: boolean }) {
useFavicon(ok ? '/favicon-ok.ico' : '/favicon-err.ico');
return null;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Lifecycle hooks are for side effects only — not for deriving render state.
- Source of truth: open
hooks/utility/useFavicon.tsfor implementation details