CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/app-framework/use-debounce-effect.ts
Views: 687
1
/*
2
This is like useEffect, except it is debounced.
3
4
Because it is debounced, the function itself can't be changed after you
5
create the hook. Thus instead of the parameters it depends on implicitly
6
changing, the function must *explicitly* take as inputs the dependency
7
list. Fortunately, typescript ensures this.
8
9
*/
10
11
import { debounce } from "lodash";
12
import type { DependencyList } from "react";
13
import { useEffect, useMemo } from "react";
14
15
export default function useDebounceEffect<T extends DependencyList>(
16
{
17
func,
18
wait,
19
options,
20
}: { func: (T) => void | (() => void); wait: number; options? },
21
deps: T
22
) {
23
const f = useMemo(() => debounce(func, wait, options), []);
24
25
useEffect(() => f(deps), deps);
26
}
27
28