Autorun and reaction cleanup function #3408
ArmorDarks
started this conversation in
Ideas
Replies: 1 comment 2 replies
-
A helper function that implements that behavior: // Runs before execution of the next autorun or on dispose
type AutorunCleanupFn = (reaction: IReactionPublic) => void
/**
* Identical to `autorun`, but allows to specify a cleanup function by returning in `view`.
* Returned function will be invoked before running the next autorun reaction,
* similar to React's `useEffect`, or on dispose.
*
* @example
* ```ts
* cleanupAutorun(() => {
* const cost = featureCostService.getCost()
*
* metrics.incUsage(cost)
*
* return () => metrics.decUsage(cost)
* })
* ```
*/
export const cleanupAutorun = (
view: (reaction: IReactionPublic) => AutorunCleanupFn | void,
opts?: IAutorunOptions,
): IReactionDisposer => {
let lastCleanupFn: AutorunCleanupFn | void
return autorun((reaction) => {
if (typeof lastCleanupFn === 'function') {
lastCleanupFn(reaction)
}
const originalReactionDispose = reaction.dispose.bind(reaction)
reaction.dispose = () => {
if (typeof lastCleanupFn === 'function') {
lastCleanupFn(reaction)
}
return originalReactionDispose()
}
lastCleanupFn = view(reaction)
}, opts)
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
That would be handy to have an easy way to clean up autoruns and reactions in a similar way React's
useEffect
hooks can be cleaned up just by returning a cleanup function.Examples
For autorun:
For reaction:
Real-life example
Without that feature, we need to have additional variables. We need to add more and more of them when we have more cases when we need some cleanup:
With that feature, it scales much better
Beta Was this translation helpful? Give feedback.
All reactions