easyReact Native#34

NetInfo connectivity check

Prompt

Use @react-native-community/netinfo to check if the device is connected to the internet. Display "Online" or "Offline" based on connectivity, and listen for changes.

Solution

const [connected, setConnected] = useState(true)
useEffect(() => {
  const unsub = NetInfo.addEventListener(state => setConnected(state.isConnected))
  return () => unsub()
}, [])
return <Text>{connected ? 'Online' : 'Offline'}</Text>
Mentor's take

On mobile, connectivity is a stream, not a status: users walk out of Wi-Fi, ride elevators, toggle airplane mode — so the correct architecture is an event subscription that keeps state current, exactly what NetInfo.addEventListener provides. It fires immediately with the current state and then on every change; the returned function is the unsubscribe, and calling it in the effect cleanup is the same non-negotiable teardown as any native event source.

The distinction that separates senior answers: isConnected means the device has a network transport (Wi-Fi association, cellular data); isInternetReachable means the internet actually answers. A captive hotel portal or a dead corporate proxy is connected-but-unreachable — the exact state where naive "online" badges lie. Which flag you gate on is a product decision, and knowing both exist is the point. The state object also carries type (wifi/cellular) and details like metered connections — the input for "don't auto-download on cellular" features.

The deeper principle: connectivity state is a UX hint, not a guard. Use it to show banners, queue mutations, and decide retry timing — but never as a substitute for handling request failure, because the status can flip between your check and your fetch. The request's own error path is the source of truth; NetInfo is how you explain it to the user. (This is also the signal React Query consumes for refetch-on-reconnect.)

Red flag: if (isConnected) fetch(...) with no failure handling — the check is instantly stale. Requests fail; NetInfo just tells you why.

Say it: "Connectivity is an event stream I subscribe to, isConnected is transport while isInternetReachable is truth, and I treat both as UX hints — the request's failure path is still the real guard."