React hook to work with abortable effects in a safe way.
An effect started with
useAbortableEffect can be aborted at any time and will
be aborted when the React component is unmounted.
While some libraries like axios and Bluebird support aborting effects, and it
wouldn't be too complicated to abort then when a component is unmounted,
useAbortableEffect does this automatically, which I think is safer, and usign
AbortController. This means effects used with
useAbortableEffect can be used anywhere: in a redux store, outside of the
React lifecycle, etc, without any dependency.
More importantly, with just
useEffect you'd likely need some way for your
effect error handler to check the mount status of your component in order to
prevent setting state or other unintended work when the abort occurs in the
context of unmounting the component, which is a bad practice.
I considered accepting a callback to handle the abort scenario, instead of throwing an error, but keeping it like the standard makes the code more portable and durable, at the cost of ergonomics.
This is a TypeScript example.