A powerful React hook based on useSyncExternalStore
that lets you subscribe to modern browser APIs like:
- 📡 network status
- 📝 text selection
- 🧭 scroll position
- 🖥 fullscreen mode
- 📱 device orientation
- 👁️ page visibility
- and many more...
Built for React 18+ with full TypeScript support and intuitive usage.
npm install use-browser-api
import { useBrowserAPI } from "use-browser-api";
const { online } = useBrowserAPI("network");
const { width, height } = useBrowserAPI("viewport");
const { text } = useBrowserAPI("selection");
const { x, y } = useBrowserAPI("scrollPosition", { ref: myRef });
All values returned are reactive and update when the related event fires.
API Name | Hook Call Example | Options (2nd param ) |
---|---|---|
network |
useBrowserAPI("network") |
— |
pageVisibility |
useBrowserAPI("pageVisibility") |
— |
deviceOrientation |
useBrowserAPI("deviceOrientation", { deviceOrientationPermission }) |
{ deviceOrientationPermission: boolean } (required on iOS/Android) |
viewport |
useBrowserAPI("viewport") |
— |
pageFocus |
useBrowserAPI("pageFocus") |
— |
scrollPosition |
useBrowserAPI("scrollPosition", { ref }) |
{ ref: RefObject<HTMLElement> } |
beforeUnload |
useBrowserAPI("beforeUnload") |
— |
fullscreen |
useBrowserAPI("fullscreen") |
— |
selection |
useBrowserAPI("selection") |
— |
screenOrientation |
useBrowserAPI("screenOrientation") |
— |
intersection |
useBrowserAPI("intersection", { ref }) |
{ ref: RefObject<HTMLElement> } |
storage |
useBrowserAPI("storage", { storageKey }) |
{ storageKey: string } |
clipboardEvents |
useBrowserAPI("clipboardEvents") |
— |
API | Returned Properties |
---|---|
network |
{ online: boolean } |
selection |
{ text: string | null } |
scrollPosition |
{ x: number, y: number } |
deviceOrientation |
{ alpha, beta, gamma } |
fullscreen |
{ active: boolean } |
intersection |
{ isIntersecting: boolean, ratio: number } |
clipboardEvents |
{ action: "copy" | "cut" | "paste", data: string } |
etc. | Varies depending on the API selected |
Check out the full example in demo-browser-api.tsx
or preview usage:
const { visible } = useBrowserAPI("pageVisibility");
useEffect(() => {
if (!visible) {
console.log("User left the page");
}
}, [visible]);
Pull requests welcome! If you'd like to add new browser APIs, feel free to open an issue or fork the repo.
MIT © ChristBM
Made with ❤️ for React developers who love the browser.