add the useInterval hook

pull/144/head
hyh123a 2022-04-24 19:19:30 +08:00
parent 5491322bd4
commit fa91142668
1 changed files with 22 additions and 0 deletions

View File

@ -0,0 +1,22 @@
import React, { useState, useEffect, useRef } from 'react';
const useInterval = (callback, delay) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
});
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
export default useInterval;