useOnlineStatus Hook
ReactJS
Medium
5 views
Problem Description
Create a hook that tracks online/offline status.
Output Format
Render a React component.
Constraints
Listen to online/offline events and update state.
Official Solution
import React, { useEffect, useState } from 'react';
function useOnlineStatus() {
const [online, setOnline] = useState(() => navigator.onLine);
useEffect(() => {
function on() { setOnline(true); }
function off() { setOnline(false); }
window.addEventListener('online', on);
window.addEventListener('offline', off);
return () => {
window.removeEventListener('online', on);
window.removeEventListener('offline', off);
};
}, []);
return online;
}
export default function App() {
const online = useOnlineStatus();
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode status</h2>
<div style={{ color: online ? '#0b5' : '#c1121f', fontWeight: 800 }}>{online ? 'Online' : 'Offline'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!