use-timeout

Calls function in given timeout

Import

Usage

Random value:

import { useState } from 'react';
import { Button, Text, Group } from '@mantine/core';
import { randomId, useTimeout } from '@mantine/hooks';

function Demo() {
  const [value, setValue] = useState('');
  const { start, clear } = useTimeout(() => setValue(randomId()), 1000);

  return (
    <Group>
      <Button onClick={start}>Start</Button>
      <Button onClick={clear} color="red">
        Clear
      </Button>
      <Text>Random value: {value}</Text>
    </Group>
  );
}

API

const { start, clear } = useTimeout(callback, delay, {
  autoInvoke: true,
});

Arguments:

  • callback – function that will be called after the timer elapses
  • delay – number of milliseconds the timer should wait before the specified function is executed
  • options: { autoInvoke } - determines whether the timer should be started on mount, defaults to false

Return object:

  • start - starts the timer
  • clear – cancels the timer

Definition

function useTimeout(
  callback: (...callbackParams: any[]) => void,
  delay: number,
  options?: {
    autoInvoke: boolean;
  }
): {
  start: (...callbackParams: any[]) => void;
  clear: () => void;
};