Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created May 10, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrysahaidak/bfb68ad1f4c7a653272529f29c1ebd46 to your computer and use it in GitHub Desktop.
Save terrysahaidak/bfb68ad1f4c7a653272529f29c1ebd46 to your computer and use it in GitHub Desktop.
Useful hook to suspend your prop change
export default function useSuspendedProp(prop, timeout = 500) {
const initialValue = useRef(prop);
const [copy, setCopy] = useState(prop);
const timeoutRef = useRef(null);
useEffect(() => {
clearTimeout(timeoutRef.current);
if (
initialValue.current === prop &&
initialValue.current !== copy
) {
setCopy(prop);
} else {
timeoutRef.current = setTimeout(() => {
setCopy(prop);
}, timeout);
}
return () => clearTimeout(timeoutRef.current);
}, [prop]);
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment