Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory leak when using functional components in Vue 2.7.14 #13212

Open
diegoexplicatis opened this issue Sep 19, 2024 · 5 comments
Open

Memory leak when using functional components in Vue 2.7.14 #13212

diegoexplicatis opened this issue Sep 19, 2024 · 5 comments

Comments

@diegoexplicatis
Copy link

diegoexplicatis commented Sep 19, 2024

Vue version

2.7.14

Link to minimal reproduction

https://github.com/diegoexplicatis/vue-2-functional-component-memory-leak

Steps to reproduce

See README.md of reproduction link

Project setup
npm install
Run project
npm run serve
How to reproduct memory leak
  1. Open base url of project (printed in console)

  2. Click on "Go to Test Component"

  3. Click on Home

  4. Open developer tools and take a heap snapshot
    take_heapsnaphot

  5. Filter for "Objects retained by detached DOM nodes"
    filter

  6. See there are detached elements, e.g. a paragraph element with id = testParagraph.
    detached

  7. Manually trigger garbage collection
    garbage_collection

  8. Take another heap snapshot and filter for "Object retained by detached DOM nodes" again

  9. See that e.g. the paragrpah is still being retained => paragraph element has leaked (it is detached from the DOM but is not being garbage collected)
    not_collected

  10. Go to FunctionalComponent.vue to line 4 and change the parameter for functional to "false"

  11. Redo steps 1 - 8

  12. See that there are not detached elements (even without manually garbage collecting) => all elements have been properly garbage collected
    no_detached

Repeatedly executing steps 2. and 3. leads to an increasing memory usage i.e. repeating the steps five times leads to five detached paragraph elements that do not get garbage collected!

What is expected?

I would expect that after executing steps 1-8, e.g. the paragraph element is not being retained anymore and has been garbage collected independent of the value for the functional parameter in FunctionComponent.vue

What is actually happening?

Instead the paragraph element is being retained when using functional: true and does not get garbage collected.

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (8) x64 Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
    Memory: 6.27 GB / 23.86 GB
Binaries:
    Node: 18.15.0 - C:\Program Files\nodejs\node.EXE
    npm: 9.5.0 - C:\Program Files\nodejs\npm.CMD
Browsers:
    Edge: Chromium (128.0.2739.79)
    Internet Explorer: 11.0.19041.4355
npmPackages:
    vue: ^2.7.14 => 2.7.16

Any additional comments?

No response

@LinusBorg
Copy link
Member

Vue 2 is no longer being maintained.

@amirafa
Copy link

amirafa commented Nov 30, 2024

Analysis of the Memory Leak
The described issue suggests that when a functional component is used (functional: true), some DOM elements created by the functional component are not being garbage collected properly. This leads to memory leaks, as detached DOM elements persist in memory.

Root Cause
Functional components in Vue 2 are stateless and instanceless. This means they do not have a Vue instance backing them. However, if a reference to a functional component's DOM node or a child exists elsewhere (e.g., in closures or event listeners), the garbage collector cannot clean up those nodes even after they are removed from the DOM.

In this specific case, enabling functional: true might result in some internal Vue references (or developer-added references) to DOM nodes, causing the memory leak. Switching functional: false creates a Vue instance, which might handle these references more effectively and ensure proper cleanup.

Steps to Mitigate
Here are some potential fixes or workarounds to resolve this issue:

  1. Avoid Using Functional Components
    If performance is not a bottleneck, avoid using functional components in Vue 2. Using standard components (functional: false) seems to prevent this issue.
  2. Manually Clean Up References
    Functional components often rely on external references (e.g., event listeners, closures). Review FunctionalComponent.vue for any code that might be retaining a reference to the DOM node or any of its children.

Example cleanup strategies:

export default {
  functional: true,
  render(h, context) {
    const onUnmount = () => {
      // Clean up references here
    };

    // Attach cleanup logic to parent or context hooks
    context.parent.$on('hook:destroyed', onUnmount);

    return h('p', { attrs: { id: 'testParagraph' } }, 'Hello');
  },
};
  1. Use Vue's destroyed Lifecycle Hooks
    Since functional components lack lifecycle hooks, ensure parent components managing them explicitly clean up any associated resources on unmount.
  2. Inspect Third-Party Libraries
    If third-party libraries are being used within the functional component, check if they properly remove references during teardown.
  3. Upgrade to Vue 3 if Possible
    Vue 3 has more robust handling of functional components and reactive system improvements, which could mitigate such issues.
    Steps for Debugging
    If the issue persists, debug further by:

Inspecting References: Use the Chrome DevTools Memory tab and inspect retained references to detached nodes to identify which closures or objects are retaining them.

Using WeakMap or WeakRef: Replace long-lived references with WeakMap or WeakRef to prevent strong references to DOM elements.

Reproduce in Isolation: Simplify the FunctionalComponent.vue to isolate the exact code causing the memory leak. For example:

export default {
  functional: true,
  render(h) {
    return h('p', { attrs: { id: 'testParagraph' } }, 'Hello');
  },
};

Long-Term Solution
This appears to be a known issue with Vue 2's handling of functional components. If feasible, consider:

Reporting the issue to Vue's GitHub repository if not already documented.
Upgrading to Vue 3, where functional components and reactivity have been significantly improved.
By avoiding functional components or ensuring all references are properly cleaned up, you can mitigate this memory leak.

@diegoexplicatis
Copy link
Author

@amirafa Thank you for the extensive answer. It makes sense that the Vue instance which is created with functional: false handles references properly while functional: true doesn't. In our project we opted for your first suggestion and removed functional components entirely. Interestingly, we were also able to mitigate the issue by rewriting the respective functional component in a js/ts file. However, we didn't analyse this further.

@rusproject
Copy link

@diegoexplicatis, @amirafa's answer is a copy-paste from chatGPT (or other LLM).
To @amirafa:
There's nothing wrong with using chatGPT or other LLMs, but you should always disclose that the provided text was generated by an LLM.

@amirafa
Copy link

amirafa commented Dec 24, 2024

@diegoexplicatis, @amirafa's answer is a copy-paste from chatGPT (or other LLM). To @amirafa: There's nothing wrong with using chatGPT or other LLMs, but you should always disclose that the provided text was generated by an LLM.

We try to help each other not showing how cool we are but you're kinda right because it might be get wrong by some people

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants
@LinusBorg @rusproject @amirafa @diegoexplicatis and others