Skip to content

Commit

Permalink
update hook useInterval
Browse files Browse the repository at this point in the history
  • Loading branch information
xizon committed Aug 29, 2024
1 parent d35060a commit 7434a42
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/utils/hooks/useInterval.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,35 @@
const App = () => {
const [count, setCount] = useState(0);
const [list, setList] = useState([]);
const { startTimer, stopTimer } = useInterval(() => {
setCount(count + 1);
}, 1000);
const { startTimer: startTimerGetList, stopTimer: stopTimerGetList } = useInterval(() => {
setList((prevState) => {
return [...prevState, Math.random()]
});
}, 1000, false);
const handleGetList = () => {
startTimerGetList();
};
useEffect(() => {
handleGetList();
}, []);
return (
<div className="app">{count}</div>
<div className="app">{count}{list.join(',')}</div>
);
};
*/
import { useEffect, useRef, useCallback } from "react";

const useInterval = (fn, delay) => {
const useInterval = (fn, delay, enabled = true) => {
const ref = useRef(null);

const intervalIdRef = useRef(null);
Expand All @@ -38,10 +53,11 @@ const useInterval = (fn, delay) => {
}, [fn]);

useEffect(() => {
startTimer();
return () => stopTimer();
}, []);

if (enabled) {
startTimer();
return () => stopTimer();
}
}, [enabled]);

return {
startTimer,
Expand Down

0 comments on commit 7434a42

Please sign in to comment.