Search code examples
vue.jsobservable

do we need to destroy/disconnect a Vue.observable?


Do we need to destroy, or disconnect the observable created when using Vue.observable()?

https://v2.vuejs.org/v2/api/#Vue-observable

Usually it's a good practice to destroy any new object and to clear timeouts and whatever can cause memory leaks on beforeDestroy. But I am wondering if the internal Vue Observer instances are also destroyed by an internal mechanism on component destroy (like the component itself), and if not how to properly stop observing and get rid of this data?

Even after looking into the source code of Vue, it is still unclear wether I should destroy an Observer. The Observer class (created internally with Vue.observable()) does not seem to have any method to stop observing and it's not documented in official Vue docs.

Please provide a reference to your answer so I can know more about it.


Solution

  • Cleanup is needed when working with some browser API's, which create resources outside of JavaScript runtime (as setInterval) or when using non-Vue libraries which create new DOM nodes.

    Vue.observable just modify object passed using Object.defineProperty() - result of the call is same JS object. And because JS is garbage collected language/runtime, no manual cleanup/destroy is needed. Objects are garbage collected automatically by runtime (no Vue) when there is no reference to it.

    Vue 3 reactive() is different because result of the call is new object - proxy - but it is still normal JS object so it is garbage collected automatically...