Skip to content

useOffline

Reaction hook to track if user is offline or not.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useOffline
sh
npx @novajslabs/cli add useOffline
sh
pnpm dlx @novajslabs/cli add useOffline

Or copy and paste the code into your project:

ts
import { useEffect, useState } from "react";

type TUseOffline = () => boolean;

export const useOffline: TUseOffline = () => {
  const [offline, setOffline] = useState<boolean | null>(null);

  useEffect(() => {
    const handleNetworkState = () => {
      setOffline(!offline);
    };
    addEventListener("offline", handleNetworkState);
    addEventListener("online", handleNetworkState);

    return () => {
      removeEventListener("online", handleNetworkState);
      removeEventListener("offline", handleNetworkState);
    };
  }, [offline]);

  return !!offline;
};
js
import { useEffect, useState } from "react";

export const useOffline = () => {
  const [offline, setOffline] = useState(null);

  useEffect(() => {
    const handleNetworkState = () => {
      setOffline(!offline);
    };
    addEventListener("offline", handleNetworkState);
    addEventListener("online", handleNetworkState);

    return () => {
      removeEventListener("online", handleNetworkState);
      removeEventListener("offline", handleNetworkState);
    };
  }, [offline]);

  return !!offline;
};

Requirements

React 16.8 or higher

Return values

offline

Type: boolean

Represents whether the user is offline (true) or online (false).

Example

tsx
import { useOffline } from "./hooks/useOffline";

const App = () => {
  const isOffline = useOffline();

  return (
    <div>{isOffline ? "You are currently offline." : "You are online."}</div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Displaying a message to the user when they go offline
  • Preventing data submission if the user is offline
  • Saving user actions locally to sync when the user goes online
  • Displaying offline-specific content or UI adjustments