In today's digitally connected world, understanding the user's online or offline status within a web application is becoming increasingly important.

Building a Custom Hook to Track User's Online/Offline Status in React

December 16, 2023

In today's digitally connected world, understanding the user's online or offline status within a web application is becoming increasingly important. Whether you need to deliver real-time updates, enhance user experience, or manage data synchronization, having insights into the user's connectivity can be pivotal. In this guide, we will walk you through the process of creating a custom React hook that effortlessly tracks a user's online or offline status.

Table of Contents

Introduction

With the internet being an integral part of modern life, web applications often need to adapt to users' varying connectivity. Imagine a chat application where you need to show when a user is online or offline, or an online document editor that needs to synchronize changes in real time. These scenarios illustrate the significance of knowing whether a user is currently online or offline. This guide will walk you through creating a custom React hook, useOnline, that addresses this need effectively.

Understanding the Code

Let's delve into the code you've provided and break it down step by step:

import { useState, useEffect } from "react";
 
const useOnline = () => {
  const [isOnline, setOnline] = useState(false);
 
  const handleOnline = () => setOnline(true);
  const handleOffline = () => setOnline(false);
 
  useEffect(() => {
    document.addEventListener("online", handleOnline);
    document.addEventListener("offline", handleOffline);
 
    return () => {
      document.removeEventListener("online", handleOnline);
      document.removeEventListener("offline", handleOffline);
    };
  }, []);
 
  return isOnline;
};
 
export default useOnline;
  1. Importing Dependencies:

    • The code begins by importing essential dependencies from the React library: useState and useEffect. These hooks are fundamental for managing state and side effects within functional components.
  2. Defining the Custom Hook:

    • The custom hook, useOnline, is crafted using the concise arrow function syntax. This hook serves to determine whether the user is presently online or offline.
  3. Initializing State:

    • Within the hook, a state variable isOnline is initialized using the useState hook. Its default value is false, assuming the user starts in an offline state.
  4. Defining Event Handlers:

    • Two event handler functions, handleOnline and handleOffline, are defined. These functions update the isOnline state based on the online and offline events, respectively.
  5. Setting Up Event Listeners:

    • The useEffect hook is employed to attach event listeners to the online and offline events on the document object. These listeners respond to changes in the user's connectivity status.
  6. Cleaning Up Event Listeners:

    • To prevent memory leaks, the useEffect hook returns a cleanup function. This function removes the event listeners when the component using the hook is unmounted.
  7. Return Statement:

    • The hook's return statement provides the isOnline state variable. This allows components using the hook to access the current online status of the user.

Using the Custom Hook

Now that we've dissected the code, let's demonstrate how to integrate this custom hook into your components:

import React from "react";
import useOnline from "./useOnline"; // Adjust the import path as needed
 
const OnlineStatus = () => {
  const isOnline = useOnline();
 
  return (
    <div>
      <p>You are currently {isOnline ? "online" : "offline"}</p>
    </div>
  );
};
 
export default OnlineStatus;

In this example, a new component named OnlineStatus is created. Within this component, the useOnline hook is harnessed to ascertain the user's current online status. Based on the value of isOnline, an appropriate message is displayed.

Conclusion

Developing custom hooks in React can significantly enhance code reusability and organization. The useOnline hook we've constructed empowers you to seamlessly track user online or offline status, offering valuable insights to optimize your application's behavior. Whether you're building a dynamic chat platform, a collaborative document editor, or any innovative application, this custom hook can serve as a valuable asset in your development toolkit. Embrace the power of custom hooks to create more efficient and effective React applications.