use-timeout

Calls function after 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} variant="outline">
Start
</Button>
<Button onClick={clear} variant="outline" 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: () => void,
delay: number,
options?: {
autoInvoke: boolean;
}
): {
start: () => void;
clear: () => void;
};