1.0.2 • Published 3 years ago

use-timers-hooks v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

use-timers-hooks

Custom Hooks to schedule execution of functions based on the timeout or interval passed.

NPM npm

Install

npm install use-timers-hooks

Usage

import { useState } from "react";
import { useInterval, useTimeout } from "use-timers-hooks";

function MyTimerComponent() {
  const [count, setCount] = useState(0);
  const [timeoutText, setTimeoutText] = useState(null);
  const { stopInterval } = useInterval((arg) => setCount(arg), 4000, [
    count + 1
  ]);
  const { stopTimeout } = useTimeout(
    (text) => {
      setTimeoutText(text);
    },
    3000,
    ["Timeout Callback Executed"]
  );
  /* PS: If you are using both interval and timeout together,
  make sure that your execution thread is not blocked */
  return (
    <div className="App">
      <div>
        <button type="button" onClick={stopInterval}>
          Stop Interval
        </button>
        <strong>Count: {count}</strong>
      </div>
      <br />
      <div>
        <button type="button" onClick={stopTimeout}>
          Stop Timeout
        </button>
        {timeoutText && <strong>{timeoutText}</strong>}
      </div>
    </div>
  );
}

Examples

To play around with these hooks, try these interactive sample apps

CodeSandbox

Parameters

All the hooks will take below parameters

ParamTypeOptionalDefaultDescription
callbackFunctionNo-The callback function to be executed once the timeout/interval has passed
timeNumberNo-Time duration for the timeout/interval in milliseconds
argsArrayYes-Array of args to be passed to the callback

Returns

An object containing below properties

PropReturn TypeDescription
stopInterval/stopTimeoutFunctionThe helper functions to end the interval/timeout programmatically

Signature

const { stopInterval } = useInterval(callback, time, args);
const { stopTimeout } = useTimeout(callback, time, args);

License

MIT © mayank8aug