useOnlineStatus: A Hook to Check Online Status in React
Jasser Mark Arioste
Hello, hustlers! Sometimes, we need to check if our React app has access to the internet or not. And if there's no access, we'll display a message or do some application logic. In this tutorial, we'll create a custom hook (useOnlineStatus
) that uses the browser's event API to detect the offline or online status of the browser.
Final Output #
Here's the final output of what we'll be making today:
Project Setup #
We'll use NextJS as our react framework for this tutorial so let's quickly get it up and running by using the following command:
npx create-next-app --ts react-online-status-tutorial
After it's done installing, use the following commands to start the local dev server:
cd react-online-status-tutorial
yarn dev
Once that's done, we can start creating our custom hook.
Creating the Custom Hook: useOnlineStatus
#
Let's create our custom hook by creating the file components/hooks/useOnlineStatus.tsx
.
import { useEffect, useState } from "react"; export const useOnlineStatus = () => { const [online, setOnline] = useState(typeof window !== "undefined" ? window.navigator.onLine : true); useEffect(() => { // create event handler const handleStatusChange = () => { setOnline(navigator.onLine); }; // listen for online and ofline event window.addEventListener("online", handleStatusChange); window.addEventListener("offline", handleStatusChange); // clean up to avoid memory-leak return () => { window.removeEventListener("online", handleStatusChange); window.removeEventListener("offline", handleStatusChange); }; }, []); return online; };
123456789101112131415161718192021222324
Explanation:
Line 4: First we use window.navigator.onLine
to set the default state of our application. navigator.online is a browser API that detects the online status of the browser.
In Lines 13-14, we listen to offline
and online
events and modify the online status by using setOnline
in line 9.
Displaying a message to the UI #
We'll use the notistack library to display toast notifications to the user when there's a change in the online status.
The notistack library is a very powerful and popular, open-source toast notification component for React. It's my go-to choice for several production-grade applications.
First, let's install it by using the command:
yarn add notistack
Next, let's modify our _app.tsx
file to use the snackbar.
// pages/_app.tsx /* Step 1: import SnackbarProvider and enqueueSnackbar */ import { SnackbarProvider, enqueueSnackbar } from "notistack"; import "../styles/globals.css"; import type { AppProps } from "next/app"; import { useOnlineStatus } from "../components/hooks/useOnlineStatus"; import { useEffect } from "react"; function MyApp({ Component, pageProps }: AppProps) { // 2. check change in online status const isOnline = useOnlineStatus(); // 3. Display snackbar on online or offline useEffect(() => { if (isOnline) { enqueueSnackbar("You are online", { variant: "success", autoHideDuration: 2000, }); } else { enqueueSnackbar("You are offline", { variant: "error", autoHideDuration: 2000, }); } }, [isOnline]); return ( <> {/* Step 4: use the SnackbarProvider */} <SnackbarProvider /> <Component {...pageProps} /> </> ); } export default MyApp;
1234567891011121314151617181920212223242526272829303132333435
Testing our App #
To test our app, we can change the online status by going to the dev tools (F12) -> Network Tab and modifying the connection speed dropdown to offline. See the screenshot below:
If we want to change it back to "online", we can just use "No throttling".
Full Code #
The full code is available at GitHub: jmarioste/react-online-status-tutorial
Conclusion #
We learned how to check the online status in React by creating a custom hook that uses the browser event API and navigator.onLine
property.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.