ColorInput: add throttling and update style to match spec
This patch adds throttling to events emitted by the native color-picker, preventing noticeable lag caused by rapid state updates. It is currently throttled to one event per 100ms, but we may want to play with this value in the future! For not it feels smooth.
This commit is contained in:
31
src/hooks/useThrottled.ts
Normal file
31
src/hooks/useThrottled.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useRef, useEffect, useCallback } from "react";
|
||||
|
||||
type Callback = (...args: any) => void;
|
||||
|
||||
export default (
|
||||
callback: Callback,
|
||||
delay: number,
|
||||
dependencies: any[] = []
|
||||
) => {
|
||||
const throttleRef = useRef<Boolean>(false);
|
||||
const callbackRef = useRef<Callback>(callback);
|
||||
|
||||
// Update the callback to be used, if it ever changes
|
||||
useEffect(() => {
|
||||
callbackRef.current = callback;
|
||||
}, [callback]);
|
||||
|
||||
return useCallback<Callback>(
|
||||
(...args) => {
|
||||
if (throttleRef.current) return;
|
||||
|
||||
throttleRef.current = true;
|
||||
callbackRef.current(...args);
|
||||
setTimeout(() => {
|
||||
throttleRef.current = false;
|
||||
}, delay);
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[delay, ...dependencies]
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user