Skip to content

Instantly share code, notes, and snippets.

Created March 17, 2021 16:47
What would you like to do?
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)) {
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