Bird
Raised Fist0
Vueframework~8 mins

Recursive components in Vue - Performance & Optimization

Choose your learning style10 modes available
Performance: Recursive components
MEDIUM IMPACT
Recursive components impact rendering performance by increasing DOM depth and triggering multiple layout calculations during recursive rendering.
Rendering a nested tree structure with Vue recursive components
Vue
<template>
  <TreeNode :node="rootNode" />
</template>

<script setup>
import { reactive } from 'vue'
import TreeNode from './TreeNode.vue'
const rootNode = reactive({
  id: 1,
  children: [/* large nested data */]
})
</script>

<!-- TreeNode.vue -->
<script setup>
  defineOptions({
    name: 'TreeNode'
  })
  const props = defineProps({
    node: Object
  })
</script>
<template>
  <div>
    <span>{{ node.id }}</span>
    <template v-if="node.children && node.children.length">
      <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
    </template>
  </div>
</template>
Adds conditional rendering to avoid unnecessary recursive calls and uses v-if to prevent rendering empty children, reducing DOM nodes.
📈 Performance GainReduces reflows by skipping empty branches; improves LCP by rendering fewer nodes initially.
Rendering a nested tree structure with Vue recursive components
Vue
<template>
  <TreeNode :node="rootNode" />
</template>

<script setup>
import { reactive } from 'vue'
import TreeNode from './TreeNode.vue'
const rootNode = reactive({
  id: 1,
  children: [/* large nested data */]
})
</script>

<!-- TreeNode.vue -->
<script setup>
  defineOptions({
    name: 'TreeNode'
  })
  const props = defineProps({
    node: Object
  })
</script>
<template>
  <div>
    <span>{{ node.id }}</span>
    <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
  </div>
</template>
Rendering deeply nested recursive components causes many nested DOM nodes and multiple reflows during initial render.
📉 Performance CostTriggers N reflows where N is the total number of nodes; blocks rendering for large trees causing slow LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Deep recursive rendering without conditionsHigh (many nested nodes)High (one per node)High (complex paint)[X] Bad
Recursive rendering with conditional checksMedium (skips empty nodes)Medium (fewer reflows)Medium (simpler paint)[!] OK
Rendering Pipeline
Recursive components cause the browser to build a deep DOM tree, triggering multiple style calculations and layout passes as each nested component renders.
→Style Calculation
→Layout
→Paint
→Composite
⚠️ BottleneckLayout is most expensive due to deep nested DOM causing multiple reflows.
Core Web Vital Affected
LCP
Recursive components impact rendering performance by increasing DOM depth and triggering multiple layout calculations during recursive rendering.
Optimization Tips
1Avoid deep recursion without limits to prevent excessive layout recalculations.
2Use v-if or similar conditional rendering to skip empty or unnecessary recursive nodes.
3Flatten data structures if possible to reduce DOM depth and improve paint times.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of using recursive components in Vue?
AExcessive JavaScript memory usage due to recursion
BIncreased network requests for each recursive call
CIncreased DOM depth causing multiple layout recalculations
DSlower CSS selector matching due to recursion
DevTools: Performance
How to check: Record a performance profile while loading the page with recursive components. Look for long scripting and layout times.
What to look for: High layout and scripting times indicate expensive recursive rendering. Check flame chart for repeated component calls.

Practice

(1/5)
1. What is the main purpose of a recursive component in Vue?
easy
A. To handle user input events more efficiently
B. To create multiple unrelated components in one file
C. To optimize component rendering speed by caching
D. To allow a component to call itself to render nested or hierarchical data

Solution

  1. Step 1: Understand recursive component concept

    A recursive component is designed to call itself to handle nested or hierarchical data structures like trees or nested menus.
  2. Step 2: Compare options with definition

    Only To allow a component to call itself to render nested or hierarchical data correctly describes this behavior. Other options describe unrelated concepts.
  3. Final Answer:

    To allow a component to call itself to render nested or hierarchical data -> Option D
  4. Quick Check:

    Recursive component = self-calling component [OK]
Hint: Recursive means component calls itself for nested data [OK]
Common Mistakes:
  • Confusing recursion with event handling
  • Thinking recursive means multiple components in one file
  • Assuming recursion is about performance optimization
2. Which of the following is the correct way to name a recursive component in Vue 3 so it can call itself?
easy
A. const TreeNode = defineComponent({ components: { TreeNode }, ... })
B. const TreeNode = defineComponent({ setup() { return {}; } })
C. const TreeNode = defineComponent({ name: 'TreeNode', ... })
D. const TreeNode = defineComponent({ recursive: true, ... })

Solution

  1. Step 1: Identify how to enable self-reference

    Vue requires a component to have a name property to call itself recursively by that name.
  2. Step 2: Check options for correct naming

    const TreeNode = defineComponent({ name: 'TreeNode', ... }) correctly sets the name property. const TreeNode = defineComponent({ setup() { return {}; } }) lacks a name, C incorrectly tries to register itself as a child, and D uses a non-existent property.
  3. Final Answer:

    const TreeNode = defineComponent({ name: 'TreeNode', ... }) -> Option C
  4. Quick Check:

    Set component name for recursion [OK]
Hint: Name the component to enable self-reference [OK]
Common Mistakes:
  • Omitting the name property
  • Trying to register the component inside itself
  • Using invalid properties like 'recursive'
3. Given this recursive component snippet, what will be rendered if node has two children?
<template>
  <div>{{ node.name }}
    <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
  </div>
</template>
medium
A. The component renders the node's name and recursively renders each child node inside nested divs
B. Only the root node's name is rendered, children are ignored
C. An infinite loop occurs causing a crash
D. The component renders the node's name but children are rendered as plain text

Solution

  1. Step 1: Understand recursive rendering logic

    The component renders the current node's name, then for each child, it calls itself recursively, rendering nested divs for children.
  2. Step 2: Analyze output for two children

    With two children, the component renders the root node's name, then two nested TreeNode components, each rendering their own names and children recursively.
  3. Final Answer:

    The component renders the node's name and recursively renders each child node inside nested divs -> Option A
  4. Quick Check:

    Recursive call renders nested children [OK]
Hint: Recursive components render nested children inside themselves [OK]
Common Mistakes:
  • Assuming children are ignored
  • Thinking recursion causes infinite loop here
  • Expecting children as plain text instead of components
4. What is the main issue with this recursive component code?
<template>
  <div>{{ node.name }}
    <TreeNode v-for="child in node.children" :node="child" />
  </div>
</template>

<script>
export default {
  name: 'TreeNode',
  props: ['node']
}
</script>
medium
A. Props are not declared correctly, should use props: { node: Object }
B. Missing :key on v-for causing rendering warnings
C. The component lacks a name property for recursion
D. Recursive call will cause infinite loop without a base case

Solution

  1. Step 1: Check for common recursive component issues

    The code correctly names the component and declares props. The recursive call is valid.
  2. Step 2: Identify missing key in v-for

    Vue requires a unique :key on elements inside v-for for efficient rendering. This is missing, causing warnings.
  3. Final Answer:

    Missing :key on v-for causing rendering warnings -> Option B
  4. Quick Check:

    Always add :key in v-for loops [OK]
Hint: Always add :key in v-for to avoid warnings [OK]
Common Mistakes:
  • Thinking name property is missing
  • Believing props declaration is invalid
  • Assuming infinite loop without base case
5. You want to display a nested comment thread using a recursive component. Each comment may have zero or more replies. Which approach correctly prevents infinite recursion and handles empty children arrays?
hard
A. In the template, use <Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply" /> and ensure comment.replies defaults to an empty array if no replies
B. Render all comments without checking children, assuming replies always exist
C. Use a v-if to stop recursion when comment.replies is undefined, but do not default to empty array
D. Avoid recursion and flatten the comment tree before rendering

Solution

  1. Step 1: Understand recursion base case

    To prevent infinite recursion, the component must handle cases where there are no children by using an empty array or conditional rendering.
  2. Step 2: Analyze options for best practice

    In the template, use <Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply" /> and ensure comment.replies defaults to an empty array if no replies uses v-for with a key and ensures replies default to an empty array, preventing errors and infinite loops. Render all comments without checking children, assuming replies always exist ignores empty children, C risks errors without default, and A avoids recursion but is not recursive component usage.
  3. Final Answer:

    Use v-for with key and default empty array for replies -> Option A
  4. Quick Check:

    Default empty array stops infinite recursion [OK]
Hint: Default children to empty array to stop recursion errors [OK]
Common Mistakes:
  • Not providing default empty array for children
  • Assuming children always exist
  • Avoiding recursion when it's the best fit
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard