Skip to content

Instantly share code, notes, and snippets.

@lilactown
Created March 17, 2021 16:47
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 lilactown/ca75ad33bff43876b94e773cc785f5c0 to your computer and use it in GitHub Desktop.
Save lilactown/ca75ad33bff43876b94e773cc785f5c0 to your computer and use it in GitHub Desktop.
function useCutoff(x, cutoff) {
// track each value of x between renders
let xPrev = useRef(x);
useEffect(() => { xPrev.current = x }, [x]);
// if the cutoff function returns true, render the previously returned value.
// else, synchronously schedule render withnew state value
let [ret, setRet] = useState(x);
if (!cutoff(xPrev.current, x)) {
setRet(x)
}
return ret;
}
// Example usage:
// maintain current value of x if it is not increasing
let x = useCutoff(x, (prev, cur) => cur - prev <= 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment