Knowing when the user goes offline
A nice touch in any app that saves or syncs: tell people the moment they drop offline, and again when they come back. Bilal Hussain showed how little it takes. Tap the button to see it (the toast slides in bottom-right):
The whole API
navigator.onLine is a boolean you can read whenever you want, and the window
fires online and offline events when it changes. Read once, subscribe to
both, done:
let online = navigator.onLine;
window.addEventListener("online", () => setOnline(true));
window.addEventListener("offline", () => setOnline(false));In React that's a tiny hook: set state from navigator.onLine on mount, update
it from the two events, and clean up the listeners. From there a pill shows the
current state and a toast slides in whenever it flips, then dismisses itself
after a few seconds.
The caveat
onLine tells you the device has a network interface that's up, not that the
internet is actually reachable. Sit behind a captive wifi portal, or have a
router with no upstream, and it'll happily report true while nothing loads.
So use it for what it's good at: the obvious, instant cases like airplane mode
or a pulled cable. When you genuinely need to know the server is reachable,
back it up with a real request (a small fetch to your API, retried with
backoff). onLine is the cheap first signal, not the final word.
Inspired by Bilal Hussain. Grab the component on the Network Status page.
Ask your agent to implement this
Read the full writeup at https://seangeng.com/writing/detecting-online-offline-status.md and implement it in my project.
It covers: Knowing when the user goes offline — navigator.onLine plus the online and offline events give you reactive connectivity in a few lines. Here's a status pill and a slide-in toast built on them, with the one caveat worth knowing.
Requirements:
- Follow the technique/approach exactly as described in the writeup.
- Adapt names, colors, and styling to my project's existing conventions.
- If it's a component, make it reusable with sensible props and TypeScript types.
- Keep it accessible: semantic HTML, keyboard support, and respect prefers-reduced-motion.
- When done, tell me which files you created or changed and how to use it.Paste into Claude Code, Codex, Cursor, or any agent. view raw .md download source .zip