useInterval
Loop run callback.
API
function useInterval(
callback: () => void,
interval?: number
): [start: () => void, cancel: () => void];
Params:
callback
: A function to be called at intervals.interval
: Optional interval time, in milliseconds.
Results:
start
: Start loop. Automatically clear the previous loop.cancel
: Cancel loop.
Example
Count: 0
import React, { useState } from "react";
import { useInterval } from "@lilib/hooks";
function Example() {
const [count, setCount] = useState(0);
const [start, cancel] = useInterval(() => {
setCount((count) => ++count);
}, 1000);
return (
<>
<button onClick={start}>Start</button>{" "}
<button onClick={cancel}>Cancel</button> Count: {count}
</>
);
}
export default Example;