Detect Time Periods in React with use-time-of-day Hook

Description:

use-time-of-day is a React Hook that calculates the current time period based on configurable hour ranges.

You can use it determine if the current time falls into specific categories like morning, afternoon, or night. The library reads the user’s system clock and returns a string value representing the active period.

Features

  • Current Period Detection: Identifies the specific time of day as a string based on the local system clock.
  • ⚙️ Customizable Hour Ranges: Accepts a configuration object to override standard time blocks with your own start and end hours.
  • 📦 Sensible Defaults: Includes pre-configured ranges for early morning, morning, afternoon, evening, and night.
  • 📐 24-Hour Format Support: Uses standard 0–23 hour integers to define boundaries for each time segment.

Use Cases

  • Dynamic User Greetings: Display “Good Morning” or “Good Evening” on a dashboard based on the user’s local time.
  • Automatic Theme Switching: Toggle between light and dark modes when the day transitions into the evening or night.
  • Time-Specific Promotions: Render banners or alert bars that only appear during business hours or specific sales periods.
  • Support Availability Status: Change the status of a chat widget to “Offline” automatically when the time enters the night range.

How to Use It

1. Add the package to your project using your preferred package manager.

npm

npm install use-time-of-day

yarn

yarn add use-time-of-day

pnpm

pnpm add use-time-of-day

2. Import the hook into your React component. Call the hook without arguments to use the default time ranges. The hook returns a string corresponding to the current time block.

import React from 'react';
import useTimeOfDay from 'use-time-of-day';
export const GreetingComponent = () => {
  const currentPeriod = useTimeOfDay();
  return (
    <div className="greeting-container">
      <h1>Hello, it is currently {currentPeriod}.</h1>
    </div>
  );
};

3. Pass a configuration object to the hook to define your own time boundaries. Each property requires a start and end hour. The start value is inclusive, while the end value covers the entire hour up to 59 minutes and 59 seconds.

In this example, “morning” lasts until 11:59:59, and “afternoon” begins exactly at 12:00:00.

import React from 'react';
import useTimeOfDay from 'use-time-of-day';
export const CustomSchedule = () => {
  const timeStatus = useTimeOfDay({
    earlyMorning: { start: 1, end: 4 },   // 01:00 to 04:59
    morning: { start: 5, end: 10 },       // 05:00 to 10:59
    afternoon: { start: 11, end: 16 },    // 11:00 to 16:59
    evening: { start: 17, end: 20 },      // 17:00 to 20:59
    night: { start: 21, end: 0 },         // 21:00 to 00:59
  });
  return (
    <div className="status-display">
      <p>Current shift: {timeStatus}</p>
    </div>
  );
};

4. The hook accepts an optional configuration object. Each key in the object represents a time period and accepts a start and end integer (0–23).

OptionTypeDefault RangeDescription
earlyMorning{ start: number, end: number }0 to 5Defines the early morning period.
morning{ start: number, end: number }6 to 11Defines the morning period.
afternoon{ start: number, end: number }12 to 17Defines the afternoon period.
evening{ start: number, end: number }18 to 19Defines the evening period.
night{ start: number, end: number }20 to 23Defines the night period.

Note: The end parameter implies the end of that hour. For example, end: 17 includes the time 17:59:59.

Related Resources

  • date-fns: A modern JavaScript date utility library for manipulating dates and times.
  • Day.js: A minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers.
  • Luxon: A library for working with dates and times in JavaScript with a focus on wrappers for standard objects.

FAQs

Q: What format does the hook return?
A: It returns a simple string matching the name of the current period, such as “morning”, “afternoon”, or “night”.

Q: How does the hook handle the end of an hour?
A: The end value covers the entire hour. If you set end: 11, the period remains active until 11:59:59.

Q: Can I omit specific ranges from the configuration?
A: The input documentation implies you should provide the full object structure when customizing to avoid gaps, though the default behavior handles standard 24-hour coverage.

Q: Does this work with server-side rendering (SSR)?
A: React hooks generally run on the client. If used in SSR, the server time might differ from the client time, causing a hydration mismatch. You should handle this by rendering the component only after the client mounts.

Add Comment