raddix

useTimeout

Execute a function after a specified amount of time.

Features

  • The timeout is automatically cleared when the component unmounts.
  • The timeout is reset when the delay changes.
  • When the callback changes, the timeout is not reset.
  • Reset function call will cancel previous timeout and start a new one.

Installation

npm i @raddix/use-timeout

Usage

Basic example

Executes the callback after 3 seconds

import { useState } from 'react';
import { useTimeout } from '@raddix/use-timeout';
export const Example = () => {
const [isReady, setIsReady] = useState(false);
useTimeout(() => {
setIsReady(true);
}, 3000);
return <div>{isReady ? 'Ready!' : 'Waiting...'}</div>;
};

API

Parameters

The hook accepts the following parameters.

ParameterDescriptionRequiredType
funcThe callback function to be executed after the specified timeoutYesfunction
delayThe duration of the timeout in milliseconds.Yesnumber
immediateIf it is true, the callback is executed immediately.Noboolean

Return value

The hook returns an object with the following properties.

PropertyDescriptionType
clearA function that can be called to clear the timeout.function
resetA function that can be called to reset the timeout. This will cancel the previous timeout and start a new one.function