-
Notifications
You must be signed in to change notification settings - Fork 0
useTimezone
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
A React hook that safely returns the user's local timezone string (e.g., "America/New_York"). It is strictly SSR-safe and guarantees hydration matches by initializing to null on the server and resolving on the client.
The simplest possible implementation.
import { useTimezone } from 'react-hook-lab';
function BasicTimezone() {
const timezone = useTimezone();
return <div>Your local timezone is: {timezone || 'Loading...'}</div>;
}Using the timezone string to format dates correctly for the user's specific location.
import { useTimezone } from 'react-hook-lab';
function EventDisplay({ serverDateString }) {
const timezone = useTimezone();
if (!timezone) return <div>Loading date...</div>;
const date = new Date(serverDateString);
const formatted = new Intl.DateTimeFormat('en-US', {
dateStyle: 'full',
timeStyle: 'long',
timeZone: timezone
}).format(date);
return <p>The event starts at: {formatted}</p>;
}An exhaustive example demonstrating how to handle the SSR hydration phase gracefully.
import { useTimezone } from 'react-hook-lab';
function AdvancedTimezoneDetector() {
const timezone = useTimezone();
// During Server-Side Rendering (SSR) and the initial client hydration,
// `timezone` is guaranteed to be `null` to prevent React hydration errors.
const isHydrated = timezone !== null;
return (
<div style={{ opacity: isHydrated ? 1 : 0.5, transition: 'opacity 0.2s' }}>
{isHydrated ? (
<div>
<h3>Client Detected!</h3>
<p>We see you are browsing from: <strong>{timezone}</strong></p>
</div>
) : (
<p>Detecting your location...</p>
)}
</div>
);
}This hook takes absolutely zero parameters.
Returns string | null:
-
Client Side: Returns the standard IANA timezone string (e.g.,
"Europe/London","America/Los_Angeles") resolved fromIntl.DateTimeFormat().resolvedOptions().timeZone. -
Server Side: Always returns
nullduring the initial server render and first hydration pass to guarantee hydration matching.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM