Delay a callback with cancel, flush, and pending state
When a user deletes a comment, many apps do not delete it right away. They show “Comment deleted. Undo” for a few seconds and only send the request when the time is up. Clicking “Undo” cancels it, and navigating away with a “Delete now” button sends it immediately. Implement a React hook, useScheduledAction, that runs a callback after a delay and lets the UI cancel it or run it early.
function useScheduledAction<Args extends unknown[]>(
callback: (...args: Args) => void,
delay: number,
): {
schedule: (...args: Args) => void;
cancel: () => void;
flush: () => void;
isPending: boolean;
}
schedule(...args) starts a timer. After delay ms, call callback(...args) once. isPending is true from the moment you schedule until the callback has run or the run was cancelled.schedule while a run is pending replaces it: the timer restarts from now and the new arguments are used. The callback runs only once.cancel() stops the pending run. The callback is not called. Cancelling when nothing is pending does nothing.flush() runs the pending callback right away with its arguments, and the timer no longer fires. Flushing when nothing is pending does nothing.callback (from the most recent render), even if it changed after schedule was called. A run that is already scheduled keeps its original delay.schedule, cancel and flush keep the same identity across renders.const { schedule, cancel, flush, isPending } = useScheduledAction(
(commentId) => api.deleteComment(commentId),
5000,
);
// t = 0 schedule('c-81') isPending true
// t = 5000 deleteComment('c-81') runs, isPending false
// t = 0 schedule('c-81')
// t = 2000 schedule('c-82') timer restarts with 'c-82'
// t = 7000 deleteComment('c-82') runs (once, never with 'c-81')
// t = 0 schedule('c-81')
// t = 1000 cancel() isPending false, nothing is deleted
// t = 0 schedule('c-81')
// t = 1000 flush() deleteComment('c-81') runs now; nothing runs at t = 5000
schedule, cancel and flush happen inside ReactDOM.flushSync.setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock and move it forward by exact amounts. Some tests count the pending timers.Object.assign(window, { useScheduledAction }); below “Do not edit below this line”. The tests use it to call your hook.