Skip to content

Latest commit

 

History

History
73 lines (61 loc) · 1.94 KB

useTimeoutFn.md

File metadata and controls

73 lines (61 loc) · 1.94 KB

useTimeoutFn

Calls given function after specified amount of milliseconds.

Several thing about it's work:

  • does not re-render component;
  • automatically cancel timeout on cancel;
  • automatically reset timeout on delay change;
  • reset function call will cancel previous timeout;
  • timeout will NOT be reset on function change. It will be called within the timeout, you have to reset it on your own when needed.

Usage

import * as React from 'react';
import { useTimeoutFn } from 'react-use';

const Demo = {
  setup() {
    const [state, setState] = useState('Not called yet');

    function fn() {
      setState(`called at ${Date.now()}`);
    }

    const [isReady, cancel, reset] = useTimeoutFn(fn, 5000);
    const cancelButtonClick = () => {
      if (isReady.value === false) {
        cancel();
        setState(`cancelled`);
      } else {
        reset();
        setState('Not called yet');
      }
    };

    return () => (
        <div>
          <div>{isReady.value !== null ? 'Function will be called in 5 seconds' : 'Timer cancelled'}</div>
          <button onClick={cancelButtonClick}>
            {' '}
            {isReady.value === false ? 'cancel' : 'restart'} timeout
          </button>
          <br/>
          <div>
            Function state: {isReady.value === false ? 'Pending' : isReady.value ? 'Called' : 'Cancelled'}
          </div>
          <div>{state.value}</div>
        </div>
    );
  }
};

Reference

const [
    isReady: Computed<boolean | null>,
    cancel: () => void,
    reset: () => void,
] = useTimeoutFn(fn: Function, ms: number = 0);
  • fn: Function - function that will be called;
  • ms: number - delay in milliseconds;
  • isReady: Computed<boolean | null> - function returning current timeout state:
    • false - pending
    • true - called
    • null - cancelled
  • cancel: ()=>void - cancel the timeout
  • reset: ()=>void - reset the timeout