- Use React Hook to check network connection status
- Originally written by Justin Travis Waith-Mair
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Jerry – FD
- Proofread by: TiaossuP, Stevens1995
Use React Hook to check the network connection status
Front-end development is a challenging endeavor. This interesting work comes out of the world of design, user experience and engineering. Our job as front-end developers is to use design, UX and UI logic to “build” a comfortable experience for the user.
As high-speed private networks become more common, normal connectivity has become commonplace, but the question that is often overlooked is what do you do and what kind of experience do you give your users when they lose their Internet connection? Many times we take connectivity for granted, but that’s not always the case. More and more pages are being displayed on mobile devices, and the network is far from stable. Wifi is certainly becoming more popular, but Wifi dead zones do exist. Even physically connected network cables can be kicked off and disconnected.
The point of this article is not to dive into UI/UX to discuss best practices when users lose connections. Instead, I’m going to help you get over the biggest hurdle: accurately determining if you’re connected in the React Component environment.
The Navigator object
Before we dive into how to use hooks to implement this specific functionality, I think it’s interesting to look at how JavaScript determines whether or not it is currently networked. This information can be found through the Navigator object. So what is a Navigator object? You can simply think of it as a read-only data that contains the current browser state and features based on your data. It has location, userAgent, and a few other properties, including whether you are currently connected. As always, I recommend that you consult the documentation for Navigator objects on MDN.
You can get the Navigator object from the global Window object: window. Navigator from here you can then get one or more properties that exist in it. What we want to get is the onLine property. I want to emphasize it here. It’s not online, it’s hump named, online.
Used in hooks
Obviously our first task is to need some state to keep track of whether we are online or not and to return it from our custom hook:
import {useState} from 'react';
function useNetwork(){
const [isOnline, setOnline] = useState(window.navigator.onLine);
return isOnline;
}
Copy the code
This is fine when the component is properly mounted, but what if the user goes offline after rendering is complete? Fortunately, we can listen for two events that are triggered to update the state. To achieve this we need to use useEffect hook:
function useNetwork(){
const [isOnline, setNetwork] = useState(window.navigator.onLine);
useEffect((a)= > {
window.addEventListener("offline",
() => setNetwork(window.navigator.onLine)
);
window.addEventListener("online",
() => setNetwork(window.navigator.onLine)
);
});
return isOnline;
};
Copy the code
As you can see, we listen for two events, offline and Online, and update the status when the event is triggered. Students who have dealt with hooks and event listeners will immediately notice two problems. The first is that we need to return a cleanup function from the useEffect callback, so React can help us remove listening for events.
The second is that to remove listeners of events in sequence, you need to provide the same function so that it knows which listeners should be removed. Passing another arrow function that looks the same does not remove event listeners as expected, even if the listeners’ look the same ‘and’ function the same ‘. So here is our updated hook:
function useNetwork(){
const [isOnline, setNetwork] = useState(window.navigator.onLine);
const updateNetwork = (a)= > {
setNetwork(window.navigator.onLine);
};
useEffect((a)= > {
window.addEventListener("offline", updateNetwork);
window.addEventListener("online", updateNetwork);
return (a)= > {
window.removeEventListener("offline", updateNetwork);
window.removeEventListener("online", updateNetwork);
};
});
return isOnline;
};
Copy the code
We now store functions inside variables so that we can drill down and unbind. Now we’re ready to create a unique experience for our users based on whether they’re online or not.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.