All hooks / Page, device, and user

useOnline

112 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

Whether the browser has a network connection, and re-renders when it changes.

Renders serverValue on the server and during hydration, then switches to navigator.onLine with no hydration mismatch.

Import

import { useOnline } from '@vincent.ri/react-tils'
// or only this hook
import { useOnline } from '@vincent.ri/react-tils/useOnline'

Usage

const online = useOnline()
return online ? null : <Banner>You are offline. Changes will sync later.</Banner>

Live demo

Turn off your network.

online

When to use it

Showing an offline banner, disabling actions that need the network, or queueing writes until the connection is back.

When not to

You need to know a server is reachable. true only means the device has a network (it can still be a captive portal or a dead Wi-Fi), so handle request failures anyway.

API

function useOnline(serverValue?: boolean): boolean
ParameterDescription
serverValueValue on the server and during hydration. Default true, since most visitors are online.

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
navigator.onLineWidely available2+12+1.5+4+18+3.2+

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).

Coming from another library?

Other libraries call this useNetworkState, useNetwork.