I want to check if user is online in a React app?

Goal

I want to display a message based on whether the user is online or offline.


Summary of the Problem

  • Error:
    Too many re-renders. React limits the number of renders to prevent an infinite loop.
  • Problem is mainly caused by a setInterval() which calls a function every 6 second that changes the state (created using useState hook)

Expected Result:

A function is called with a set interval that checks whether a user is online or offline and then displays a message if a user is offline


What I have tried:

export default function CardContainer() {
 const [isOnline, set_isOnline] = useState(true);
 function InternetErrMessagenger() {
    if (navigator.onLine===true) set_isOnline(true);
    if (navigator.onLine===false) set_isOnline(false);
 }
 setInterval(InternetErrMessagenger(), 6000);
 return (
    // the <InternetChecker /> component contains a message that gets displayed when offline
    {isOnline !== true ? <InternetChecker /> : ""}
 )

A Glimpse of my effort:

enter image description here

NOTE: I was thinking of using the useEffect hook to solve this problem but could not make out how to do so. If you are thinking of any other way of addressing this problem, please share with me.

80 thoughts on “I want to check if user is online in a React app?”

Leave a Comment