Atom destructors
See original GitHub issueHey,
I’m using RecoilJS to store references to WebAssembly values. These values must be manually freed by calling a .free()
method on the reference in order to avoid memory leaks[1]. As far as I can tell, there’s currently no way to reliably call a destructor on a Recoil value[2].
My current approach is to define a selector wrapper around an atom with a set
function that frees the previous value of the atom. However, when the Recoil root is unmounted, the set
function isn’t invoked, and thus the values are leaked. Furthermore, I’m noticing race conditions during updates. I reckon it might be due to Recoil yielding control to the event loop between the time a value is set and the time React re-renders components with that value. During that time, it’s possible a component effect will try to use the previous recoil value, since freed. This can happen in a requestAnimationFrame
callback.
It’d be nice to be able to define a destructor callback for atom values that gets called once the RecoilRoot tree has updated with the new value, or once the RecoilRoot that held that value has unmounted.
[1] https://rustwasm.github.io/wasm-bindgen/contributing/design/exporting-rust-struct.html [2] I’m aware WeakRef somewhat fixes this issue, but it isn’t available in Safari (yet?).
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:6 (3 by maintainers)
Top GitHub Comments
Hmm, yeah, freeing previous value on set also could be unsafe with React Concurrent Mode, which may still be rendering part of the tree using the previous value.
We’re looking at memory management to free up resources when atoms are no longer used, but this is a slightly different situation where you care about specific atom values no longer being used. (cc @davidmccabe )
It looks like Atom Effects (experimental) would be a great solution to this problem.