43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useRef } from "react";
|
|
|
|
export function useDebouncedChange(onChange: (html: string) => void, debounceMs: number) {
|
|
const timerRef = useRef<number | null>(null);
|
|
const optimisticHtmlRef = useRef<string>("");
|
|
|
|
const flushChange = useCallback(
|
|
(nextHtml: string) => {
|
|
optimisticHtmlRef.current = nextHtml;
|
|
onChange(nextHtml);
|
|
},
|
|
[onChange]
|
|
);
|
|
|
|
const scheduleChange = useCallback(
|
|
(nextHtml: string) => {
|
|
optimisticHtmlRef.current = nextHtml;
|
|
|
|
if (!debounceMs || debounceMs <= 0) {
|
|
onChange(nextHtml);
|
|
return;
|
|
}
|
|
|
|
if (timerRef.current) window.clearTimeout(timerRef.current);
|
|
timerRef.current = window.setTimeout(() => {
|
|
timerRef.current = null;
|
|
onChange(optimisticHtmlRef.current);
|
|
}, debounceMs);
|
|
},
|
|
[debounceMs, onChange]
|
|
);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (timerRef.current) window.clearTimeout(timerRef.current);
|
|
};
|
|
}, []);
|
|
|
|
return { scheduleChange, flushChange, optimisticHtmlRef };
|
|
}
|