ReactJS Program to useOnlineStatus Hook with Explanation
ReactJS
Medium
Hooks & Effects
29 views
1 min read
83 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around hook, online, offline. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a hook that tracks online/offline status.
Input Format
No input.
Output Format
Render a React component.
Constraints
Listen to online/offline events and update state.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
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>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a hook that tracks online/offline status.
Input / Output
Output
Render a React component.
Constraints
Listen to online/offline events and update state.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Difficulty
Medium
ReactJS
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!