Never Leave Users in the Dark: Implement Offline Detection in Your React App with Context Api

Never Leave Users in the Dark: Implement Offline Detection in Your React App with Context Api

ยท

3 min read

In the era of Progressive Web Apps (PWAs) and an increasing focus on user experience, ensuring your application gracefully handles offline scenarios is crucial. This blog post will guide you through implementing offline detection in your React.js web app using the Context API. By the end, users will see a dedicated page prompting them to turn on the internet when they go offline.

Step 1: Setting Up the Project

npx create-react-app offline-detection
cd offline-detection
npm start

This will set up a new React project and start the development server.

Step 2: Creating the Context

We'll create a context to manage the online/offline state. Create a new file called NetworkContext.js in the src directory.

// src/NetworkContext.js
import React, { createContext, useState, useEffect } from 'react';

const NetworkContext = createContext();

const NetworkProvider = ({ children }) => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const updateOnlineStatus = () => setIsOnline(navigator.onLine);

    window.addEventListener('online', updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);

    return () => {
      window.removeEventListener('online', updateOnlineStatus);
      window.removeEventListener('offline', updateOnlineStatus);
    };
  }, []);

  return (
    <NetworkContext.Provider value={{ isOnline }}>
      {children}
    </NetworkContext.Provider>
  );
};

export { NetworkContext, NetworkProvider };

Step 3: Wrapping the App with NetworkProvider

Wrap your application with the NetworkProvider to provide network state to all components.

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { NetworkProvider } from './NetworkContext';

ReactDOM.render(
  <NetworkProvider>
    <App />
  </NetworkProvider>,
  document.getElementById('root')
);

Step 4: Creating the Offline Page

// src/OfflinePage.js
import React from 'react';

const OfflinePage = () => (
  <div style={{ textAlign: 'center', marginTop: '20%' }}>
    <h1>You're Offline</h1>
    <p>Please check your internet connection and try again.</p>
  </div>
);

export default OfflinePage;

Step 5: Implementing the Offline Detection

Now, let's modify the App.js to conditionally render the offline page based on the network state.

// src/App.js
import React, { useContext } from 'react';
import './App.css';
import { NetworkContext } from './NetworkContext';
import OfflinePage from './OfflinePage';

const App = () => {
  const { isOnline } = useContext(NetworkContext);

  return (
    <div className="App">
      {isOnline ? (
        <div>
          <h1>Welcome to the Online App</h1>
          <p>Your content goes here.</p>
        </div>
      ) : (
        <OfflinePage />
      )}
    </div>
  );
};

export default App;

Final result

offline

With these steps, you've successfully implemented offline detection in your React.js web app using the Context API. Now, your users will be informed when they lose internet connectivity and can take appropriate action to restore it. This simple yet effective feature enhances the overall user experience and ensures your app remains user-friendly in all scenarios.

Amazon Prime Video Hello GIF by primevideoin


Thanks a lot for reading till the end ๐Ÿ™ If you liked the article, please give likes and share it with your others.

Email: atul19251@gmail.com

LinkedIn: https://www.linkedin.com/in/atul-kumar-singh-673357102/

Web: https://iamatul.netlify.app/

Did you find this article valuable?

Support Dev Station by becoming a sponsor. Any amount is appreciated!

ย