tezvyn:

React Native NetInfo: Know Your Connection State

AI-drafted, machine-checkedSource: github.comintermediate

The NetInfo API is your app's network sensor, telling you if you're online and whether you're on WiFi or cellular. Use it to show an 'offline' banner or defer large downloads. The main footgun: `isConnected` only confirms a local link, not server reachability.

WHY IT EXISTS: Mobile apps often need to behave differently based on network conditions. Without a connection, features might fail silently, creating a poor user experience. NetInfo provides a unified way to query the network state to build more robust, context-aware applications.

THE MENTAL MODEL: Think of NetInfo as a dashboard light for your app's internet connection. It tells you if the connection is on (isConnected), what kind of connection it is (type, e.g., 'wifi' or 'cellular'), and whether the internet is likely reachable. It's a listener you subscribe to for real-time updates.

HOW IT WORKS: NetInfo is a community-maintained library that wraps native Android, iOS, and other platform APIs into a single, consistent JavaScript interface for React Native. You typically use the useNetInfo hook in your components. This hook returns an object with the current network state and automatically re-renders your component whenever the state changes, like when a user connects to WiFi or loses cell signal.

WHEN TO USE IT: Use NetInfo to improve user experience in response to connectivity changes. Three common use cases: first, displaying a global banner that says "You are offline"; second, disabling form submission buttons when no connection is detected to prevent failed requests; third, pausing large file uploads and resuming them only when the device is on a non-cellular connection to save the user's data.

WHEN NOT TO USE IT: Do not use NetInfo as the sole method for verifying if your server is reachable. The isInternetReachable flag is a good hint, but it can be wrong. A device can be connected to a WiFi network with no actual internet backhaul (like in a hotel before logging in). The only true test of reachability is to actually make a network request to your server and handle the success or failure.

ONE CANONICAL EXAMPLE: A common pattern is to use the useNetInfo hook to conditionally render UI. For example: import { useNetInfo } from "@react-native-community/netinfo"; const MyComponent = () => { const netInfo = useNetInfo(); return ( !netInfo.isConnected && <Text>You are offline.</Text> ); }; This snippet shows a text warning only when the device is not connected to any network.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.