Skip to content

useTimeout

This hook makes setTimeout easy to use and control with some useful methods.

Parameters

  1. the setTimeout callback function.
  2. and some options:
NameTypeDescription
timeoutNumberthe setTimeout timeout in ms.
startOnMountBooleanstart automatically when the component is mounted (default is false).
depsArraydependency array (default is [])

Props And Methods

start(), cancel(), and toggle()

Use these two methods to start and cancel the timeout, or toggle between them using toggle:

ts
const timeout = useTimeout(() => console.log('Hello!'), { timeout: 1000 });

timeout.start(); // running
timeout.cancel(); // canceled

timeout.toggle(); // running
timeout.toggle(); // canceled

timeout.toggle(true); // running
timeout.toggle(false); // canceled
const timeout = useTimeout(() => console.log('Hello!'), { timeout: 1000 });

timeout.start(); // running
timeout.cancel(); // canceled

timeout.toggle(); // running
timeout.toggle(); // canceled

timeout.toggle(true); // running
timeout.toggle(false); // canceled

isRunning

this value indicates whether the timeout is running or not:

ts
const timeout = useTimeout(() => console.log('Stoped by setTimeout.'), {
  timeout: 500,
  startOnMount: true
});

timeout.isRunning; // true

timeout.cancel();

timeout.isRunning; // false
const timeout = useTimeout(() => console.log('Stoped by setTimeout.'), {
  timeout: 500,
  startOnMount: true
});

timeout.isRunning; // true

timeout.cancel();

timeout.isRunning; // false

Example Usage

tsx
import { useTimeout } from 'react-pre-hooks';

export default function Hello() {
  const timeout = useTimeout(() => console.log('done!'), {
    timeout: 1000,
    startOnMount: true
  });

  return (
    <main>
      <div>{timeout.isRunning ? 'Wait...': 'Hello!'}</div>
      <button onClick={() => timeout.toggle()}>
        {timeout.isRunning ? 'Cancel' : 'Start'}
      </button>
    </main>
  );
}
import { useTimeout } from 'react-pre-hooks';

export default function Hello() {
  const timeout = useTimeout(() => console.log('done!'), {
    timeout: 1000,
    startOnMount: true
  });

  return (
    <main>
      <div>{timeout.isRunning ? 'Wait...': 'Hello!'}</div>
      <button onClick={() => timeout.toggle()}>
        {timeout.isRunning ? 'Cancel' : 'Start'}
      </button>
    </main>
  );
}

Released under the MIT License.