React Hook for Real-Time Data
Client-side times are notoriously unreliable. This custom React Hook fetches the trusted server time and the user's timezone based on their IP address, perfect for hydration-safe apps.
REACT
import { useState, useEffect } from 'react';
const useServerTime = () => {
const [timeData, setTimeData] = useState(null);
useEffect(() => {
fetch('https://time.now/developer/api/ip')
.then(res => res.json())
.then(data => setTimeData(data))
.catch(err => console.error(err));
}, []);
return timeData;
};
// Usage
export default function ClockComponent() {
const time = useServerTime();
if (!time) return <div>Loading...</div>;
return (
<div>
<p>Location: {time.timezone}</p>
<p>Server Time: {time.datetime}</p>
</div>
);
}
Why use Time.Now for Frontend?
- Prevents hydration mismatches
- CORS enabled for localhost
- Auto-detects user location