Voyz's Studio.

React自定义Hook--useInterval

字数统计: 87阅读时长: 1 min
2021/02/10 Share

React自定义Hook–useInterval

避免在useEffect里setInterval时,因未清除计时器而导致的两次副作用之间的相互影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useEffect, useRef } from 'react';

export default function useInterval(callback, delay) {
const _callback = useRef();

useEffect(() => {
_callback.current = callback;
});

useEffect(() => {
function clock() {
_callback.current();
}
if (delay !== null) {
let id = setInterval(clock, delay);
return () => clearInterval(id);
}
}, [delay]);
}
CATALOG
  1. 1. React自定义Hook–useInterval