CodeBlanks Logo Icon CodeBlanks

NetInfo

Learn network state with NetInfo.

The NetInfo package

To learn whether the app is online or offline you use the @react-native-community/netinfo package. This package gives the network state instantly; the isConnected field tells whether the device is connected to the internet. With Expo you install it with npx expo install @react-native-community/netinfo.

The package is used in two ways. First, an instant query: const state = await NetInfo.fetch(); this gives the current network state. Second, a subscription: NetInfo.addEventListener((state) => ...); this is called whenever the network state changes. The subscription returns a function; when called, the subscription is removed. In offline apps knowing the network state is critical.

Import and fetch

The package comes as a default export: import NetInfo from '@react-native-community/netinfo'. For an instant query you use await NetInfo.fetch(). The result is an object; the isConnected field carries the connection state, the type field carries the network type (wifi, cellular).

Example: const state = await NetInfo.fetch(); console.log(state.isConnected). This logs the current connection. If state.isConnected is true the device is online, if false it is offline. Based on this info the app can make a network request or fall back to the local cache.

Practice Query the network state

Complete the empty checkOnline function. Call const state = await NetInfo.fetch(). Return the connection state with return state.isConnected.

Starter code

App.js
import NetInfo from '@react-native-community/netinfo';

export async function checkOnline() {
  // query the network state and return isConnected
}

Sample solution

App.js
const state = await NetInfo.fetch();
return state.isConnected;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does NetInfo provide?

  • Only file storage
  • Network state info Correct answer
  • Only camera
  • Only location

Explanation: NetInfo provides network state info.

2 Write the import statement

Question
import ____ from '@react-native-community/netinfo';
Answer
import NetInfo from '@react-native-community/netinfo';

Explanation: NetInfo is the default export.

3 Match each part to its role

Term Meaning
NetInfo.fetch() Instant query
addEventListener Sets up subscription
isConnected Connection state
type Network type

All lessons in Advanced