Skip to content

Instantly share code, notes, and snippets.

@joeldenning
Created September 22, 2021 23:00
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 joeldenning/ecd67557356f05071b5061813385d7e2 to your computer and use it in GitHub Desktop.
Save joeldenning/ecd67557356f05071b5061813385d7e2 to your computer and use it in GitHub Desktop.
use imperative action
function useImperativeAction(action) {
const [status, setStatus] = useState(1);
useEffect(() => {
// negative means just cancel without re-running
if (status >= 0) {
return action();
}
}, [status]);
const doAction = useCallback(() => {
setStatus((oldStatus) => {
if (oldStatus < 0) {
// positive means cancel last and re-run action
setStatus(1);
} else {
// ensure we don't set to the same value as before
setStatus(oldStatus + 1);
}
});
}, []);
const cancel = useCallback(() => {
// negative means just cancel without re-running
setStatus(-1);
}, []);
return [doAction, cancel];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment