Menu

gitpiper

useNavigatorOnLine react Code Snippet in 2023

hooksstateeffectintermediate

Last Updated: 28 January 2023

Checks if the client is online or offline.

  • Create a function, getOnLineStatus, that uses the NavigatorOnLine 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'));

react snippet similar to useNavigatorOnLine For You in January 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️