react-usekit

Beta

useTimeout

A custom hook that sets up a timeout to call a callback function after a specified delay.

Installation

npx react-usekit@latest init

Select: hooks → TypeScript or JavaScript → path -> useTimeout

Usage

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

function DelayedMessage() {
  const [showMessage, setShowMessage] = useState(false);
  const [isActive, setIsActive] = useState(true);

  useTimeout(
    () => {
      setShowMessage(true);
    },
    isActive ? 3000 : null
  );

  return (
    <div>
      {showMessage ? (
        <p>This message appeared after 3 seconds!</p>
      ) : (
        <p>Waiting for message...</p>
      )}
      <button onClick={() => setIsActive(!isActive)}>
        {isActive ? "Cancel" : "Start"} Timeout
      </button>
      <button onClick={() => setShowMessage(false)}>Reset</button>
    </div>
  );
}

Pass null as the delay to cancel the timeout. The hook automatically cleans up the timeout when the component unmounts.

API

Parameters

ParameterTypeDescription
callback() => voidThe function to be called after the delay
delaynumber | nullThe time in milliseconds before calling the function. If null, the timeout is cancelled

Returns

This hook doesn't return anything.