You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

react-network-information

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-network-information

A React hook that allows you to access the browser's Network Information API and handle network connection changes.

0.1.4
latest
npm
Version published
Weekly downloads
6
-64.71%
Maintainers
1
Weekly downloads
 
Created
Source

React Network Information

A React hook that allows you to access the browser's Network Information API and handle network connection changes.

Installation

You can install the package via npm:

npm install react-network-information

Usage

The hook returns the current NetworkInformation object and can also take an optional callback function that will be called whenever the network connection changes.

import { useNetworkInformation } from "use-network-information"

function MyComponent() {
  const networkInfo = useNetworkInformation()

  return (
    <div>
      <p>Effective Type: {networkInfo?.effectiveType}</p>
      <p>Rtt: {networkInfo?.rtt}</p>
    </div>
  )
}

You can also pass an optional callback function that will be called whenever the network connection changes:

import { useNetworkInformation } from "use-network-information"

function MyComponent() {
  const handleConnectionChange = (event: Event) => {
    console.log("Network connection changed:", event.currentTarget)
  }

  const networkInfo = useNetworkInformation(handleConnectionChange)

  return (
    <div>
      <p>Effective Type: {networkInfo?.effectiveType}</p>
      <p>Rtt: {networkInfo?.rtt}</p>
    </div>
  )
}

Compatibility

The Network Information API is supported by most modern browsers, but may not be supported by older browsers. To ensure compatibility, you can check if the navigator.connection property exists before using the hook.

Example

Here is an example of how you can use the hook to show a message to the user when their connection is slow:

import { useNetworkInformation } from "use-network-information"

function MyComponent() {
  const networkInfo = useNetworkInformation()

  return <div>{networkInfo?.effectiveType === "slow-2g" && <p>Your connection is slow</p>}</div>
}

References

  • https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API

FAQs

Package last updated on 14 Jan 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts