Open Hooks

useTimeout

Run a function after a delay with cancel/reset controls.

useTimeout

Run a function once after a delay. Useful for animations, debounced UI actions, splash screens, etc.


📦 Installation

No external dependency needed

🧠 Purpose

useTimeout lets you execute a callback after a given delay and provides control to cancel or reset it.


💡 Use Cases

  • Splash screens
  • Auto-close modals
  • Triggering animation after delay
  • Reminders or delayed alerts

📁 Hook Code

useTimeout.ts
import { useEffect, useRef, useCallback } from "react";

export function useTimeout(callback: () => void, delay: number | null) {
  const savedCallback = useRef(callback);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay === null) return;
    const id = setTimeout(() => savedCallback.current(), delay);
    return () => clearTimeout(id);
  }, [delay]);
}
useTimeout.js
import { useEffect, useRef } from "react";

export function useTimeout(callback, delay) {
  const savedCallback = useRef(callback);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay === null) return;
    const id = setTimeout(() => savedCallback.current(), delay);
    return () => clearTimeout(id);
  }, [delay]);
}

🧪 Example

import { useState } from "react";
import { useTimeout } from "@/hooks/useTimeout";

export default function DelayedMessage() {
  const [visible, setVisible] = useState(false);

  useTimeout(() => setVisible(true), 3000);

  return <p>{visible ? "Hello after 3 seconds!" : "Waiting..."}</p>;
}

🧩 Hook Signature

function useTimeout(callback: () => void, delay: number | null): void;

📝 Parameters

PropTypeDefault
delay
number | null
-
callback
() => void
-

🎯 Returns

No Return Value

This hook does not return anything. It runs the callback after the specified delay and handles cleanup internally.


🧯 Visual Timeline

Timeout Flow

After mounting, the callback runs once after the specified delay.

Render Delay = 3000ms
Timer starts...
After 3s callback is executed

🏁 Summary

  • ✅ Declarative timeout logic
  • ✅ Useful for delayed UI updates
  • ✅ Works with cancel/reset behavior
  • ✅ Easily testable

🙋 Contribution

Found a bug or improvement? Submit a PR on GitHub