MCPcopy Create free account
hub / github.com/QuarkGluonPlasma/react-course-code / useInterval

Function useInterval

closure-trap/src/App4.tsx:3–27  ·  view source on GitHub ↗
(fn: Function, time: number)

Source from the content-addressed store, hash-verified

1import { useEffect, useState, useRef, useCallback, useLayoutEffect } from 'react';
2
3function useInterval(fn: Function, time: number) {
4 const ref = useRef(fn);
5
6 useLayoutEffect(() => {
7 ref.current = fn;
8 });
9
10 let cleanUpFnRef = useRef<Function>();
11
12 const clean = useCallback(() =>{
13 cleanUpFnRef.current?.();
14 }, []);
15
16 useEffect(() => {
17 const timer = setInterval(() => ref.current(), time);
18
19 cleanUpFnRef.current = ()=> {
20 clearInterval(timer);
21 }
22
23 return clean;
24 }, []);
25
26 return clean;
27}
28
29function App() {
30 const [count, setCount] = useState(0);

Callers 1

AppFunction · 0.85

Calls 1

useEffectFunction · 0.90

Tested by

no test coverage detected