Skip to content

useTimezone

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useTimezone

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.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation.

import { useTimezone } from 'react-hook-lab';

function BasicTimezone() {
  const timezone = useTimezone();

  return <div>Your local timezone is: {timezone || 'Loading...'}</div>;
}

Common (Standard Usage)

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>;
}

Advanced (All Parameters)

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>
  );
}

API Reference

Parameters

This hook takes absolutely zero parameters.

Return Object

Returns string | null:

  • Client Side: Returns the standard IANA timezone string (e.g., "Europe/London", "America/Los_Angeles") resolved from Intl.DateTimeFormat().resolvedOptions().timeZone.
  • Server Side: Always returns null during the initial server render and first hydration pass to guarantee hydration matching.

Clone this wiki locally