Open tangye1234 opened 8 months ago
Thanks for the issue @tangye1234. Do I understand correctly that the difference in approach is that there the microtask would only be run after the double renders have been committed?
I like that the implementation no longer has a dependency on global WeakSet
which means that multiple calls of useDisposable
could be called. We've worked with microtasks before in Fluent for debouncing https://github.com/microsoft/fluentui/blob/master/packages/react-components/priority-overflow/src/debounce.ts.
One of the pitfalls of microtasks is that they operate outside of the effect cycle - which means that in userland there's no way to know when dispose has happened. It can also play badly with unit testing frameworks since disposal can occur after the the test has unmounted. See specifically here for the caveat that we added for unit test environments https://github.com/microsoft/fluentui/blob/ae3b77e7995d2ed37ae8d153308f82b4f3940e03/packages/react-components/priority-overflow/src/debounce.ts#L10-L14
Would you like to make a PR contribution to this repo and we could try to release a pre-release version to test it out for a while?
After using the
Disposable
mode, I was unable to completely resolve the issues with React 18 because it requires creating the disposable instance during the React rendering phase, where lifecycle management isn't as robust as within the useEffect hook.However, I've now developed a truly versatile
useDisposable
hook that can be seamlessly integrated into any scenario. Check out this demonstration:Now when I use like this:
in dev strict mode of react 18, browser console prints:
server console prints:
and if I unmount the component, the browser console prints:
So I think we should replace this method instead.