Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network Status Detect In Reactjs

i am new in Reactjs my problem is that i have to detect the network status if wifi or internet connection is connected or disconnected

i tried using the below code but it wont detect network status correctly it always return false value

please help me

and here is my code and codesandbox.io

import React, { useEffect, useState } from 'react';

function App() {
  const [status, setStatus] = useState(null)

  useEffect(() => {
    window.addEventListener('online', () => setStatus(navigator.onLine))
    return () => window.removeEventListener('online', () => setStatus(navigator.onLine))
  })

  return (
    <div>
      <h2>Network Status Detector</h2>
      {status ? <div style={{ top: 50, position: "absolute" }}>Network Connected</div> : <div style={{ top: 50, position: "absolute"}}>Network Disconnected</div>}
    </div>
  )
}

export default App;
like image 754
Henry Avatar asked Oct 27 '25 01:10

Henry


1 Answers

You need to use the same function reference for the event listener else it won't clean up on unmount/effect cleanup.

Here's a sample code for this

export default function App() {
  return <NetworkStatus />;
}
const NetworkStatus = () => {
  const [status, setStatus] = useState(true);

  useEffect(() => {
    function changeStatus() {
      setStatus(navigator.onLine);
    }
    window.addEventListener("online", changeStatus);
    window.addEventListener("offline", changeStatus);
    return () => {
      window.removeEventListener("online", changeStatus);
      window.removeEventListener("offline", changeStatus);
    };
  }, []);

  return status ? "Online" : "Offline";
};

Look how we're not using an arrow function here. We can either create the function inside the useEffect or a function returned by useCallback.

https://codesandbox.io/s/restless-cache-50wg5?file=/src/App.js

like image 89
Pavan Avatar answered Oct 28 '25 16:10

Pavan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!