useEffect cleanup not being called
ebramanti opened this issue · 3 comments
Don't have a simple example to share at the moment, but curious if this library supports calling the cleanup of the useEffect
hook when there are no more instances of the hook in the React DOM.
Hi @ebramanti, many thanks to your issue!
This is not a bug, it's a subtle feature 😊
Now instances exist regardless of the state of the DOM and always exist after the first call. This gives an advantages in testing, makes it possible to work with shared logic before building a DOM (for example, to start loading the current user, even before the first render occurs).
But... I feel there is a need for the logic you describe.
The free
function is now implemented. This allows you to destroy the shared state whenever you want.
import { free } from “use-between”;
free(useCounter); // Any shared hook
But I feel that this is not quite what is needed. Maybe we can add something like that to the library API:
const App = () => {
const { count } = useBetween(useCounter, { arc: true });
return <h1>{count}</h1>;
}
"arc" means - automatic reference counter.
What do you think about?
Hmm.
Hi @ebramanti again!
In the previous "arc" option, I don't like the confusion that arises when using the same shared hook with and without the "arc" option. It is also not clear how to deal with the “get” operation.
get(useCounter).inc()
With this in mind, I propose the following solution:
const App = () => {
const { count } = useBetween(useCounter, { freeOnUnmount: true });
return <h1>{count}</h1>;
}
In fact, it will be an alias to the following code:
const App = () => {
const { count } = useBetween(useCounter);
useEffect(() => () => free(useCounter), []);
return <h1>{count}</h1>;
}
What do you think about?
looks good to me.