Skip to content
All writing

July 16, 2021 · 1 min read

Offline screen in React Native with NetInfo

Detect connectivity changes in React Native and render an offline screen using @react-native-community/netinfo — six small steps.

#react-native#android

So you want to check internet connection and show an offline screen if you are disconnected?

Steps:

  1. Install the netinfo package:
npm install --save @react-native-community/netinfo
  1. Import and declare:
let NetInfoSubscription = null
  1. Initialize state:
const [connectionStatus, setConnectionStatus] = useState(false)
  1. Handle connection changes:
const handleConnectionChange = (state) => {
  setConnectionStatus(state.isConnected)
}
  1. Inside useEffect, subscribe:
NetInfoSubscription = NetInfo.addEventListener(handleConnectionChange)
return () => {
  NetInfoSubscription
}
  1. Render conditionally:
connectionStatus ? <MainContent /> : <OfflineScreen />

That's it.