Skip to content

useTimeout

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

useTimeout

A declarative setTimeout hook that safely handles cleanup. It automatically clears the timeout when the component unmounts and guarantees that you always have access to the latest state inside your callback.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, which starts the timeout immediately on mount.

import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';

function BasicTimeout() {
  const [show, setShow] = useState(true);

  useTimeout(() => {
    setShow(false);
  }, 5000);

  if (!show) return null;
  return <div>This will disappear in 5 seconds!</div>;
}

Common (Standard Usage)

Manually stopping or restarting the timeout based on user interaction.

import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';

function AutoLogout() {
  const [loggedOut, setLoggedOut] = useState(false);

  const { restart, clear } = useTimeout(() => {
    setLoggedOut(true);
  }, 60000); // 1 minute of inactivity

  if (loggedOut) return <div>You have been logged out due to inactivity.</div>;

  return (
    <div onMouseMove={restart} onKeyDown={restart}>
      <p>Move your mouse or press a key to reset the inactivity timer.</p>
      <button onClick={clear}>Disable Auto-Logout</button>
    </div>
  );
}

Advanced (All Parameters)

An exhaustive example checking the active status and dynamically controlling the execution flow.

import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';

function AdvancedTimeout() {
  const [logs, setLogs] = useState<string[]>([]);
  
  const { start, clear, isActive } = useTimeout(() => {
    setLogs(prev => [...prev, `Timeout triggered at ${new Date().toLocaleTimeString()}`]);
  }, 3000);

  return (
    <div>
      <p>Status: {isActive() ? 'Running' : 'Stopped'}</p>
      <button onClick={start} disabled={isActive()}>Start Timer</button>
      <button onClick={clear} disabled={!isActive()}>Stop Timer</button>
      <ul>
        {logs.map((log, i) => <li key={i}>{log}</li>)}
      </ul>
    </div>
  );
}

API Reference

Parameters

  • callback (Required)
    • Type: () => void
    • Description: The function to execute after the delay. This callback is internally wrapped in a ref, so you do not need to wrap it in useCallback to prevent infinite loops. It always has access to the latest state.
  • delay (Required)
    • Type: number
    • Description: The delay in milliseconds before executing the callback.

Return Object

Returns UseTimeoutReturn:

  • start (() => void): Function to manually start or restart the timeout from 0.
  • clear (() => void): Function to manually cancel the running timeout.
  • restart (() => void): Alias for start(). Clears and starts the timeout.
  • isActive (() => boolean): Returns true if the timeout is currently counting down, or false if it has fired or been cleared.

Clone this wiki locally