React useNavigatorOnLine hook

React, Hooks, State, Effect · Nov 16, 2020

Checks if the client is online or offline.

  • Create a function, getOnLineStatus, that uses the Navigator.onLine web API to get the online status of the client.
  • Use the useState() hook to create an appropriate state variable, status, and setter.
  • Use the useEffect() hook to add listeners for appropriate events, updating state, and cleanup those listeners when unmounting.
  • Finally return the status state variable.
const getOnLineStatus = () =>
  typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'
    ? navigator.onLine
    : true;

const useNavigatorOnLine = () => {
  const [status, setStatus] = React.useState(getOnLineStatus());

  const setOnline = () => setStatus(true);
  const setOffline = () => setStatus(false);

  React.useEffect(() => {
    window.addEventListener('online', setOnline);
    window.addEventListener('offline', setOffline);

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

  return status;
};
const StatusIndicator = () => {
  const isOnline = useNavigatorOnLine();

  return <span>You are {isOnline ? 'online' : 'offline'}.</span>;
};

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • React useSSR hook

    Checks if the code is running on the browser or the server.

    React, Hooks · Mar 10, 2021

  • React useMediaQuery hook

    Checks if the current environment matches a given media query and returns the appropriate value.

    React, Hooks · Oct 13, 2021

  • React useSearchParam hook

    Tracks the browser's location search param.

    React, Hooks · Oct 13, 2021