Building a Real-Time Online Status Checker with React using useSyncExternalStore
Tags: react, usesyncexternalstore, webdev, javascript
Published: 2024-03-09 11:09:25

Hello, Dev.to community! In this tutorial, we'll explore how to create a real-time online status checker in a React application using the powerful `useSyncExternalStore` hook.

Let's dive in step by step to understand the code and implement this feature in your React projects. Ready? Let's get started!

## Step 1: Setting up the Project

First, create a new React project or use an existing one.

```bash
npx create-react-app myapp
```
or if you want to integrate in another web project, make sure you have the `react` library installed. Additionally, ensure that you have `useSyncExternalStore` from the 'react' library. You can install it using:

```bash
npm install react
```


## Step 2: Creating the useOnlineStatus Hook

Now, let's implement the `useOnlineStatus` hook. This hook utilizes `useSyncExternalStore` to manage the online status in real-time.

```jsx
// useOnlineStatus.js
import { useSyncExternalStore } from 'react';

export function useOnlineStatus() {
  const isOnline = useSyncExternalStore(subscribe, getSnapshot);
  return isOnline;
}

function getSnapshot() {
  // value getter
}

function subscribe(callback) {
  // subscribe logic
}
```

The `getSnapShot` function is used to get the value which will be returned by the hook.
```jsx
//...other code

function getSnapshot() {
  return navigator.onLine;
}

//...other code
```
Here we get the online status using the navigator.onLine which returns the boolean value whether the client is connected to internet or not.

The `subscribe` function is provided a callback as parameter and we need to call the callback function whenever we want to hit the `getSnapshot` function to get the desired value.
```jsx
//...other code

function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

```
Here we subscribe to the `online` and `offline` event using their respective `event listeners` so that it triggers the `getSnapshot` function whenever there is a change in internet connectivity i.e if the user goes online or offline.

**Final code for useOnlineStatus hook**
```jsx
// useOnlineStatus.js
import { useSyncExternalStore } from 'react';

export function useOnlineStatus() {
  const isOnline = useSyncExternalStore(subscribe, getSnapshot);
  return isOnline;
}

function getSnapshot() {
  return navigator.onLine;
}

function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}
```



## Step 3: Implementing the Online Status Checker

Now that we have our hook, let's use it in our component.

```jsx
// App.js
import React from 'react';
import { useOnlineStatus } from './useOnlineStatus';

function App() {
  const isOnline = useOnlineStatus();

  return (
    <div>
      <h1>Online Status Checker</h1>
      <h2>{isOnline ? "✅ Online" : "❌ Disconnected"}</h2>;
    </div>
  );
}

export default App;
```

## Conclusion

Congratulations! You've successfully built a real-time online status checker using React's `useSyncExternalStore` hook. Feel free to experiment with this feature in your projects and let me know your thoughts in the comments.

We have a youtube video explaining this as well. Please feel free to watch it.
{% youtube SZlwJEPoJa8 %}

If you found this tutorial helpful, please give it a like, share it with your fellow developers, and don't forget to follow for more React tips and tutorials. Happy coding!