import { useEffect, useRef } from "react"; /** * Runs `run` once each time `value` leaves `watched`, however it leaves. Not on first render, and always with the * latest `run`, so a caller can pass a function it rebuilds every render. */ export const useRunWhenLeaving = (value: T, watched: T, run: () => void): void => { const previous = useRef(value); const latestRun = useRef(run); latestRun.current = run; useEffect(() => { if (previous.current === watched && value !== watched) latestRun.current(); previous.current = value; }, [value, watched]); };