Pull to refresh

React Custom Hook: useOnlineStatus

Level of difficultyMedium
Reading time2 min

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useOnlineStatus" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

import { useState } from "react"
import useEventListener from "../useEventListener/useEventListener"

export default function useOnlineStatus() {
    const [online, setOnline] = useState(navigator.onLine)
    useEventListener("online", () => setOnline(navigator.onLine))
    useEventListener("offline", () => setOnline(navigator.onLine))
    return online

One of the main advantages of "useOnlineStatus" is its simplicity. By importing and using this hook in your component, you can effortlessly access the online status of the user. The hook internally uses the "navigator.onLine" property to determine the initial online status and dynamically updates it whenever the user's connectivity changes.

To use this hook, all you need to do is call it within your functional component, just like the "OnlineStatusComponent" example demonstrates. It returns a boolean value indicating whether the user is currently online or offline. You can then utilize this information to provide real-time feedback to your users or make decisions based on their online status.

import useOnlineStatus from "./useOnlineStatus"

export default function OnlineStatusComponent() {
    const online = useOnlineStatus()
    return <div>{online.toString()}</div>

The "useOnlineStatus" hook can find applications in a wide range of scenarios. For instance, you can enhance user experience by displaying a visual indicator when the user loses their internet connection, allowing them to take appropriate actions. Additionally, you can conditionally render certain components or trigger specific behaviors based on the user's online status. The possibilities are endless, and this hook opens up new opportunities for building robust and responsive React applications.

Full Version | React Custom Hooks: https://habr.com/en/articles/746760/