This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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