Skip to content

Instantly share code, notes, and snippets.

@patrickcze
Last active August 18, 2023 12:59
Show Gist options
  • Save patrickcze/2814e93a7988654be4268232f80ff6a9 to your computer and use it in GitHub Desktop.
Save patrickcze/2814e93a7988654be4268232f80ff6a9 to your computer and use it in GitHub Desktop.
A basic hook to indicate if the user is online or offline
import React, { useState, useEffect, useContext } from "react";
const OnlineStatusContext = React.createContext(true);
export const OnlineStatusProvider: React.FC = ({ children }) => {
const [onlineStatus, setOnlineStatus] = useState<boolean>(true);
useEffect(() => {
window.addEventListener("offline", () => {
setOnlineStatus(false);
});
window.addEventListener("online", () => {
setOnlineStatus(true);
});
return () => {
window.removeEventListener("offline", () => {
setOnlineStatus(false);
});
window.removeEventListener("online", () => {
setOnlineStatus(true);
});
};
}, []);
return (
<OnlineStatusContext.Provider value={onlineStatus}>
{children}
</OnlineStatusContext.Provider>
);
};
export const useOnlineStatus = () => {
const store = useContext(OnlineStatusContext);
return store;
};
@jeffrafter
Copy link

Thanks for this hook! I made a couple of changes https://gist.github.com/jeffrafter/8bab08f3efaac5e8a9350cd9dc05b3cc

  • make the listeners const (easier to read and more clear when removing the event listener)
  • check the online status for the default state (don't use true)

These changes helped when using this in combination with next-pwa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment