0
0
Vueframework~15 mins

h function for creating vnodes in Vue - Deep Dive

Choose your learning style9 modes available
Overview - h function for creating vnodes
What is it?
The h function in Vue is a way to create virtual nodes (vnodes) that represent elements or components in the user interface. Instead of writing HTML directly, you use h to describe what the UI should look like in a programmatic way. This helps Vue efficiently update the real webpage by comparing these virtual nodes.
Why it matters
Without the h function, Vue would have to manipulate the real webpage directly every time something changes, which is slow and inefficient. The h function lets Vue build a lightweight virtual version of the UI first, so it can quickly find and apply only the necessary changes. This makes apps faster and smoother for users.
Where it fits
Before learning the h function, you should understand basic Vue components and how templates work. After mastering h, you can explore advanced topics like render functions, JSX in Vue, and custom directives that manipulate vnodes.
Mental Model
Core Idea
The h function creates a simple JavaScript object that describes a UI element or component, which Vue uses to efficiently update the real webpage.
Think of it like...
Imagine building a LEGO model using instructions on paper before snapping bricks together. The h function writes those instructions, so you know exactly what to build without trial and error.
h(tag, props, children)
  │      │       └─ Array or string representing child nodes
  │      └─ Object with attributes, event listeners, etc.
  └─ String or component representing the element type

Example:

h('button', { onClick: handleClick }, 'Click me')

This creates a vnode for a button with a click event and label.
Build-Up - 7 Steps
1
FoundationWhat is a Virtual Node (VNode)?
🤔
Concept: Introduce the idea of a virtual node as a simple JavaScript object representing a UI element.
A virtual node (vnode) is like a blueprint for a UI element. Instead of creating the actual button or div on the webpage, Vue creates a vnode describing it. This vnode includes the element type, its properties, and its children. It’s a lightweight way to represent the UI in memory.
Result
You understand that vnodes are the building blocks Vue uses internally to manage the UI efficiently.
Understanding vnodes is key because the h function’s job is to create these blueprints, which Vue then uses to update the real page.
2
FoundationBasic Syntax of the h Function
🤔
Concept: Learn the simple form of the h function: tag, props, and children.
The h function takes three main inputs: 1. tag: a string like 'div' or a component reference 2. props: an object with attributes or event handlers 3. children: text or an array of other vnodes Example: h('p', { id: 'intro' }, 'Hello world') This creates a vnode for a paragraph with an id and text.
Result
You can write simple vnodes using h to describe UI elements programmatically.
Knowing the three parts of h helps you build any UI structure without templates.
3
IntermediateUsing h with Components
🤔Before reading on: do you think h can only create HTML elements or also Vue components? Commit to your answer.
Concept: Learn that h can create vnodes for both HTML elements and Vue components.
Besides HTML tags, h can take a Vue component as the first argument. This lets you create vnodes that represent custom components, passing props and children just like with elements. Example: import MyButton from './MyButton.vue' h(MyButton, { color: 'blue' }, 'Press me') This creates a vnode for the MyButton component with a color prop and slot content.
Result
You can use h to build complex UIs by nesting components programmatically.
Understanding that h works with components unlocks powerful dynamic UI creation beyond static HTML.
4
IntermediateChildren Variations in h Function
🤔Before reading on: do you think children in h must always be strings, or can they be arrays or functions? Commit to your answer.
Concept: Explore the different types of children h accepts: strings, arrays, or even functions (slots).
Children can be: - A string for simple text - An array of vnodes for multiple children - A function returning vnodes for scoped slots Example: h('ul', null, [ h('li', null, 'Item 1'), h('li', null, 'Item 2') ]) This creates a list with two items.
Result
You can create nested and dynamic UI structures using h’s flexible children argument.
Knowing children can be arrays or functions lets you build complex, reusable UI patterns.
5
IntermediateProps and Event Handling in h
🤔
Concept: Learn how to pass attributes and event listeners via the props object in h.
The props object can include HTML attributes like id, class, or custom props for components. Event listeners use the 'on' prefix. Example: h('button', { id: 'save', onClick: () => alert('Saved!') }, 'Save') This creates a button with an id and a click event handler.
Result
You can control element behavior and appearance directly through h’s props.
Understanding props in h is essential for interactive and styled UI elements.
6
AdvancedRender Functions Using h
🤔Before reading on: do you think render functions replace templates completely or just complement them? Commit to your answer.
Concept: Learn how h is used inside render functions to build UI without templates.
Render functions are JavaScript functions that return vnodes created by h. They give full control over UI rendering. Example: export default { render() { return h('div', null, 'Hello from render') } } This replaces the template with a programmatic UI description.
Result
You can write Vue components without templates, using JavaScript logic to build UI.
Knowing render functions lets you create dynamic and conditional UIs that templates can’t easily express.
7
ExpertPerformance and Reactivity with h
🤔Before reading on: does using h always make Vue slower or can it improve performance? Commit to your answer.
Concept: Understand how Vue optimizes vnodes created by h for fast updates and reactivity.
Vue tracks changes in reactive data and compares new vnodes from h with old ones (diffing). It updates only what changed in the real DOM. Using h directly can sometimes improve performance by avoiding template parsing and enabling fine control. However, misuse can cause unnecessary re-renders if keys or reactive dependencies are missing.
Result
You can write highly optimized components by controlling vnode creation and updates with h.
Understanding Vue’s vnode diffing and reactivity helps you write efficient render functions and avoid common performance pitfalls.
Under the Hood
The h function creates a vnode object containing the element type, props, and children. Vue’s virtual DOM system uses these vnodes to build a tree representing the UI. When reactive data changes, Vue generates new vnodes and compares them to the old ones using a diff algorithm. It then applies only the minimal changes to the real DOM, improving speed and reducing flicker.
Why designed this way?
Vue’s h function and virtual DOM were designed to separate UI description from actual DOM manipulation. Direct DOM updates are slow and error-prone. By using vnodes, Vue can batch updates and minimize costly operations. This design balances developer flexibility with performance, allowing both template and programmatic UI creation.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│  h() call   │──────▶│  vnode obj  │──────▶│  vnode tree │
└─────────────┘       └─────────────┘       └─────────────┘
       │                      │                    │
       ▼                      ▼                    ▼
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│ tag, props, │       │  diff old   │       │  patch DOM  │
│ children    │       │  vs new     │       │  efficiently│
└─────────────┘       └─────────────┘       └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the h function create real DOM elements immediately? Commit to yes or no.
Common Belief:The h function directly creates and inserts real DOM elements on the page.
Tap to reveal reality
Reality:The h function only creates virtual nodes, which are lightweight JavaScript objects. Vue later uses these to update the real DOM efficiently.
Why it matters:Believing h creates real DOM immediately can confuse learners about Vue’s rendering process and lead to misuse of h in performance-critical code.
Quick: Can you use h only inside render functions, or anywhere in Vue? Commit to your answer.
Common Belief:The h function can only be used inside render functions and nowhere else.
Tap to reveal reality
Reality:While h is mainly used in render functions, it can also be used in setup functions or anywhere you want to create vnodes programmatically.
Why it matters:Knowing h’s flexibility allows developers to build dynamic UIs and reusable logic beyond just render functions.
Quick: Does passing children as a string always work the same as passing an array? Commit to yes or no.
Common Belief:Children passed as a string or as an array of vnodes behave identically in all cases.
Tap to reveal reality
Reality:Strings become text nodes, while arrays allow multiple children and nested structures. They behave differently in rendering and updates.
Why it matters:Misunderstanding children types can cause bugs in UI structure and unexpected rendering results.
Quick: Does using h always improve performance compared to templates? Commit to yes or no.
Common Belief:Using h instead of templates always makes Vue apps faster.
Tap to reveal reality
Reality:Using h can improve performance in some cases but can also cause slower updates if not used carefully with keys and reactive data.
Why it matters:Assuming h is always faster can lead to premature optimization and complex code that is harder to maintain.
Expert Zone
1
When using h with components, passing the correct keys is crucial for Vue’s diffing algorithm to avoid unnecessary re-renders.
2
The props object in h supports special keys like 'ref' and 'class' that Vue treats differently under the hood.
3
Using functions as children in h enables scoped slots, a powerful pattern for reusable and flexible components.
When NOT to use
Avoid using h for simple static UIs where templates are clearer and more maintainable. Use templates for most cases and switch to h only when you need dynamic or programmatic control. For complex JSX-like syntax, consider using Vue’s JSX support instead of raw h calls.
Production Patterns
In production, h is often used in render functions for dynamic components, custom directives, or libraries that generate UI programmatically. Frameworks like Vue Router and Vuex sometimes use h internally to create UI elements. Experts combine h with reactive data and lifecycle hooks to build performant, flexible components.
Connections
React.createElement
Similar pattern for creating virtual DOM nodes in React.
Understanding Vue’s h function helps grasp React’s createElement, as both create virtual nodes for efficient UI updates.
Functional Programming
h function embodies declarative UI description, a core idea in functional programming.
Knowing functional programming concepts clarifies why h returns immutable vnode objects instead of changing the DOM directly.
Compiler Design
Vue’s template compiler transforms templates into render functions that use h.
Understanding compilers helps see how high-level templates become low-level h calls, bridging human-friendly syntax and machine-efficient code.
Common Pitfalls
#1Passing children as a plain object instead of an array or string.
Wrong approach:h('div', null, { text: 'Hello' })
Correct approach:h('div', null, 'Hello')
Root cause:Misunderstanding that children must be a string, array, or function, not a plain object.
#2Forgetting to add keys when rendering lists with h.
Wrong approach:h('ul', null, items.map(item => h('li', null, item.name)))
Correct approach:h('ul', null, items.map(item => h('li', { key: item.id }, item.name)))
Root cause:Not knowing keys help Vue track elements during updates, causing inefficient re-renders.
#3Using h inside templates instead of render functions.
Wrong approach: