日本語

How to Show Online or Offline Status on a React Screen

​​React​custom hook,Playwright,TypeScript,useSyncExternalStore

When the browser's network drops, I show an "Offline" label next to the heading, with "Offline since 13:19" below it. When the connection comes back, I show "Back online" for 3 seconds and then hide it. The network status is read from navigator.onLine and the online and offline events.

However, navigator.onLine being true does not guarantee that the server can be reached. When I stopped the test server, the display still said "Online". To check whether the server is reachable, you have to send an actual request. I also tested how to write that check, described later in the article.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, converted them with esbuild, and served them from a test server written in Node.js. I switched the network state with Playwright's context.setOffline(). I did not test what happens when you actually unplug Wi-Fi or a cable, Firefox and Safari, mobile browsers, or server-side rendering.

In the heading "Cat notes" (the label is in Japanese), a light-blue "Online" badge (the label is in Japanese) sits to the right. When the "Turn off network" button (the label is in Japanese) is pressed, the badge changes to a gray "Offline" badge (the label is in Japanese), and "Offline since 13:19" (the label is in Japanese) appears below it. When the "Turn on network" button (the label is in Japanese) is pressed, the badge returns to "Online" and "Back online" (the label is in Japanese) appears. About 3 seconds after reconnecting, the message disappears.
Turning the network off switches the display to offline, and turning it back on shows the 'back online’ message for only 3 seconds

In the GIF, the "Test controls" box below it (the label is in Japanese), the click counter in the upper right, the seconds count after reconnecting, and the cursor and click-position circle were overlaid for the recording. The buttons in the box only switch the browser's network through Playwright, and they are unrelated to the component in this article. I made the badge and the message pink only at the moment they change.

A hook that reads the network status

I read the network status with useOnlineStatus, which has the same form as the example in React's official reference that subscribes to a browser API. I used the same hook in an earlier article, "How to Make a React App Work Offline with a Service Worker", to show an offline banner.

ts
import { useSyncExternalStore } from 'react';

function subscribe(callback: () => void) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

export function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine, // value in the browser
    () => true, // value when rendering on the server
  );
}

According to MDN's description of navigator.onLine, when this value changes, an online or offline event fires on window. In my test environment, calling context.setOffline(true) fired one offline event, and navigator.onLine became false. Setting it back to false fired an online event, and the value returned to true.

The third argument is the value used when generating HTML on the server. The server has no navigator.onLine, a browser API, so it always returns true, as described in the official reference's section on server rendering. In this article's tests, I rendered only in the browser.

A component that shows the disconnect time and "Back online"

useOnlineStatus only tells you whether you are online right now. The time the connection was lost and whether the connection has just been restored are tracked by the component when the value changes.

tsx
import { useEffect, useRef, useState } from 'react';
import { useOnlineStatus } from './useOnlineStatus';

const timeFormat = new Intl.DateTimeFormat('ja-JP', { hour: '2-digit', minute: '2-digit' });

export function ConnectionStatus() {
  const isOnline = useOnlineStatus();
  const [offlineSince, setOfflineSince] = useState<Date | null>(null);
  const [justReconnected, setJustReconnected] = useState(false);
  const prevOnline = useRef(isOnline);

  useEffect(() => {
    if (prevOnline.current === isOnline) return; // do nothing on the first render
    prevOnline.current = isOnline;
    if (!isOnline) {
      setOfflineSince(new Date());
      setJustReconnected(false);
      return;
    }
    setJustReconnected(true);
    const id = setTimeout(() => setJustReconnected(false), 3000);
    return () => clearTimeout(id);
  }, [isOnline]);

  let message = '';
  if (!isOnline) {
    message = offlineSince
      ? `${timeFormat.format(offlineSince)} からオフラインです`
      : 'オフラインです';
  } else if (justReconnected) {
    message = 'オンラインに戻りました';
  }

  return (
    <>
      <span className={isOnline ? 'badge online' : 'badge offline'}>
        {isOnline ? 'オンライン' : 'オフライン'}
      </span>
      <p role="status" className="connection-message" data-online={isOnline}>
        {message}
      </p>
    </>
  );
}

prevOnline holds the value from the last time the effect ran. Right after the page opens, the previous and current values are the same, so nothing happens. Without this check, "Back online" would appear just from opening the page.

When the connection drops, the current time is stored in offlineSince. When it comes back, justReconnected becomes true, and a timer sets it back to false after 3 seconds.

The message <p> stays on the screen even when the text is empty. As MDN's description of the status role explains, an element with role="status" is meant to announce changes in its content without interrupting the user. I did not test screen reader announcements in this article.

In my test environment, the display changed as follows.

Action Badge Message
Right after opening the page Online (none)
Right after turning off the network Offline Offline since 13:19
Right after turning it back on Online Back online
2 seconds after turning it back on Online Back online
3.3 seconds after turning it back on Online (none)

I ran the development build with StrictMode enabled and got the same results.

When the network drops again right after reconnecting

If the connection goes up and down repeatedly in a short time, the page can go offline again while the timer that clears "Back online" is still pending. In the code above, when isOnline changes, the cleanup function from the previous run cancels that timer. As React's useEffect reference explains, when a dependency changes, React runs the previous run's cleanup function before running the effect with the new value.

In my test, I turned the network off, turned it back on after 0.5 seconds, and turned it off again 1 second later. The display immediately changed to "Offline since 13:19" and stayed that way 3 seconds later. The old timer never cleared the offline message.

When the page is opened while offline

When a page is opened while offline, for example one served by a Service Worker, the time of disconnection is unknown. In that case offlineSince stays null, so the component shows only "Offline" with no time.

I tested this by replacing navigator.onLine with a version that always returns false before opening the page. The badge showed "Offline" and the message showed "Offline". I did not actually open the page while the network was offline.

Even when navigator.onLine is true, the server may not be reachable

MDN's description of navigator.onLine says that browsers and operating systems determine the value differently. For example, if the device is connected to a LAN, it may be treated as online and return true even when that LAN cannot reach the internet. For this reason, MDN recommends using this value only as a hint that the user may be offline, not as a reason to disable features.

In my test environment, after the page was open, I stopped only the test server. navigator.onLine stayed true, and no event fired. The badge still said "Online".

In the heading "Cat notes" (the label is in Japanese), the badge still says "Online" (the label is in Japanese). After pressing the "Check server connection" button (the label is in Japanese) below it, the message "The server cannot be reached" (the label is in Japanese) appears.
After stopping the test server. The badge still says online, but the request does not reach the server

The label at the top of the image above was added for the recording. The text "The server cannot be reached" was made pink for the recording.

To check whether the server can be reached, you have to send an actual request. The checkServer function below sends a HEAD request to /api/ping and returns true if the response has a 2xx status. On the test server, /api/ping returns an empty 204 response.

ts
export async function checkServer(): Promise<boolean> {
  try {
    const res = await fetch('/api/ping', {
      method: 'HEAD',
      cache: 'no-store',
      signal: AbortSignal.timeout(5000),
    });
    return res.ok;
  } catch {
    return false; // network error, or timeout after 5 seconds
  }
}

With cache: 'no-store', as MDN's description of Request.cache explains, the browser fetches from the server without consulting its cache. This prevents an old cached response from making the check report that the server is reachable.

The signal option takes a signal created by AbortSignal.timeout(). If there is no response within 5 seconds, the request is aborted and fetch throws an error. This keeps the display from staying at "Checking…" forever when no response ever comes back.

The following component calls this function from a button.

tsx
import { useState } from 'react';
import { checkServer } from './checkServer';

type Result = 'idle' | 'checking' | 'ok' | 'ng';

export function ServerCheck() {
  const [result, setResult] = useState<Result>('idle');

  async function handleClick() {
    setResult('checking');
    setResult((await checkServer()) ? 'ok' : 'ng');
  }

  return (
    <div className="server-check">
      <button onClick={handleClick} disabled={result === 'checking'}>
        サーバーとの接続を確かめる
      </button>
      <p data-result={result}>
        {result === 'checking' && '確かめています…'}
        {result === 'ok' && 'サーバーにつながりました'}
        {result === 'ng' && 'サーバーにつながりません'}
      </p>
    </div>
  );
}

These are the results when I pressed the button under different conditions. I measured the time from pressing the button until the result appeared.

Condition navigator.onLine Result Time taken
Server is running true The server is reachable 115 ms
Server is stopped true The server cannot be reached 51 ms
Browser network is turned off false The server cannot be reached 61 ms
Server does not respond true The server cannot be reached 5092 ms

When the server was stopped, the connection was refused immediately (the browser error was ERR_CONNECTION_REFUSED). When the network was turned off, the browser failed immediately without sending the request (ERR_INTERNET_DISCONNECTED). In both cases, the result came back right away. When the server did not respond, the result showed "cannot be reached" only after the 5-second timeout.

Point

Use navigator.onLine for hint-style displays like the badge, and decide whether you can send data based on the result of fetch. Even when no offline indicator is shown, a request can still fail.

​Posted by 86