Skip to content

Instantly share code, notes, and snippets.

@diegohaz
Last active April 21, 2023 18:10
Show Gist options
  • Save diegohaz/46de1e11fca973de846afd0fb827cab7 to your computer and use it in GitHub Desktop.
Save diegohaz/46de1e11fca973de846afd0fb827cab7 to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from "react";
export function usePerceptibleValue<T>(
value: T,
{ delay = 0, minDuration = 350 } = {}
) {
const [perceptibleValue, setPerceptibleValue] = useState(value);
const nextThresholdRef = useRef(0);
useEffect(() => {
const remaining = Math.max(0, nextThresholdRef.current - Date.now());
const timer = setTimeout(() => {
nextThresholdRef.current = Date.now() + minDuration;
setPerceptibleValue(value);
}, delay + remaining);
return () => clearTimeout(timer);
}, [value, delay, minDuration]);
return perceptibleValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment