react-use
react-use copied to clipboard
feat: add useSignallingEffect for idiomatic side-effect cancellation
Description
useSignallingEffect runs an effect with an AbortSignal, which is automatically aborted when the effect is cleaned up. This provides an idiomatic way of cancelling side-effects.
Useful as a shorthand for common operations that require clean up or cancellation and support AbortSignal, like adding event listeners:
useSignallingEffect((signal) => {
window.addEventListener('resize', () => {}, { signal });
}, []);
Or fetching data:
useSignallingEffect(
(signal) => {
(async () => {
try {
const res = await fetch(`/api/user/${userId}`, { signal });
setData(await res.json());
} catch (err) {
if (!signal.aborted) {
throw err;
}
}
})();
},
[userId]
);
Type of change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as before)
Checklist
- [x] Read the Contributing Guide
- [x] Perform a code self-review
- [x] Comment the code, particularly in hard-to-understand areas
- [x] Add documentation
- [x] Add hook's story at Storybook
- [x] Cover changes with tests
- [x] Ensure the test suite passes (
yarn test) - [x] Provide 100% tests coverage
- [x] Make sure code lints (
yarn lint). Fix it withyarn lint:fixin case of failure. - [x] Make sure types are fine (
yarn lint:types).
Note: there's an expected exhaustive-deps eslint rule violation, which is inherent to all useEffect-style hooks. I didn't ignore it with a comment since other hooks don't do that.