Render functions and JSX

Advanced · 16 min

What templates compile into, writing vnodes by hand with h(), passing slots and listeners in code, functional components, and using JSX in Vue.

Before thisSlots and scoped slotsHow Vue reactivity works

Program With Erik · 16 min

Render functions and JSX

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Program With ErikReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Every Vue template is compiled into a render function that returns virtual DOM nodes; writing that function yourself with h() trades the template's readability for the full power of JavaScript.
  • h(type, props, children) creates a vnode: type is a tag name or a component, props hold attributes, classes, styles, and on-prefixed listeners, and children are a string, an array of vnodes, or, for components, an object of slot functions.
  • A setup function can return a render function instead of state; setup still runs once, while the returned function re-runs whenever the reactive state it reads changes.
  • Template features become plain JavaScript in render functions: v-if is a ternary, v-for is map with keys, v-model is a modelValue prop plus an onUpdate:modelValue listener, and directives are applied with withDirectives.
  • Hand-written render functions skip the template compiler's optimizations, such as hoisted static content and patch flags, so templates remain the default and render functions are for genuinely dynamic structure or library code.
  • JSX in Vue needs @vitejs/plugin-vue-jsx, and it differs from React's JSX: it uses class rather than className, supports v-model and v-show, and passes slots as an object of functions.

What a template really is

You’ve written templates since the first lesson, but the browser never sees them. At build time, Vue’s compiler turns each template into a JavaScript function that returns a description of the DOM: a tree of virtual nodes, or vnodes. This template:

<template>
  <button class="btn" @click="count++">Clicked {{ count }} times</button>
</template>

compiles to something close to this:

import { h } from 'vue'

function render() {
  return h('button', { class: 'btn', onClick: () => count.value++ }, `Clicked ${count.value} times`)
}

Vue runs that render function inside a reactive effect, the mechanism from how Vue reactivity works. Every ref it reads becomes a dependency. When one changes, the function re-runs, produces a new vnode tree, and the runtime patches the real DOM with the difference.

Render functions are the layer templates sit on. Usually you let the compiler write them. Sometimes you want to write them yourself.

h(): creating vnodes by hand

h (short for “hyperscript”, meaning JavaScript that produces HTML) takes up to three arguments:

import { h } from 'vue'

h('div')                                   // just a type
h('div', { id: 'main', class: ['card', { active: isActive.value }] })
h('a', { href: '/docs', onClick: track }, 'Docs')   // props + text child
h('ul', items.value.map((item) => h('li', { key: item.id }, item.name)))
h(MyButton, { size: 'lg', onSelect: handleSelect }, () => 'Click me')
  • type: a tag name string, or a component object you’ve imported.
  • props: attributes, DOM properties, class and style (same object and array forms as class and style bindings), component props, and listeners. A listener is a prop named on plus the capitalized event name: onClick, onSelect, onUpdate:modelValue.
  • children: a string, an array of vnodes, or, for a component, slots (covered below).

Props can be skipped when there are none: h('p', 'Hello') works.

One rule catches people out: a vnode can appear in the tree only once. To render the same thing twice, call h twice, for example with Array.from({ length: 3 }, () => h('li', 'Row')).

Where a render function goes

<script setup> is built around a template and has no way to return a render function. You write the component with defineComponent (or a plain export default) and return a function from setup:

import { defineComponent, h, ref } from 'vue'

export default defineComponent({
  props: { start: { type: Number, default: 0 } },
  setup(props, { slots, emit }) {
    const count = ref(props.start) // runs once

    return () =>                     // re-runs on every reactive change
      h('div', { class: 'counter' }, [
        h('button', { onClick: () => { count.value++; emit('change', count.value) } }, '+1'),
        h('span', ` ${count.value} `),
        slots.default?.(),
      ])
  },
})

This split is the key idea. setup runs once and owns the state, exactly as in <script setup>. The returned arrow function is the render function, and it closes over that state. If you’re coming from React, this is the biggest difference from a JSX function component: React re-runs the whole component on every render, while Vue only re-runs the render function.

When setup returns a render function, it can’t also return state for a template, and nothing is visible to a parent’s template ref unless you call expose() from the setup context.

Translating template features

Everything a directive does in a template becomes ordinary JavaScript:

// v-if / v-else
ok.value ? h('p', 'Yes') : h('p', 'No')

// v-for (keys still matter)
h('ul', todos.value.map((t) => h('li', { key: t.id }, t.text)))

// v-model on a component
h(MyInput, {
  modelValue: name.value,
  'onUpdate:modelValue': (v) => (name.value = v),
})

// event modifiers: do the work yourself
h('form', { onSubmit: (e) => { e.preventDefault(); save() } })

// a template ref
const input = ref(null)
h('input', { ref: input })

Custom directives are applied with withDirectives, passing [directive, value, arg, modifiers] tuples:

import { h, withDirectives } from 'vue'
withDirectives(h('input'), [[vFocus], [vPin, 40, 'left', { animate: true }]])

Components registered globally by name (say, by a plugin) are looked up with resolveComponent('RouterLink'). Built-ins like Transition, KeepAlive, and Teleport are imported from 'vue' and passed to h like any component.

Slots in render functions

Slots are where render functions earn their keep, and they run in both directions.

Rendering the slots you receive: slots from the setup context is an object of functions. Call one to get its vnodes, passing slot props for a scoped slot:

return () => h('ul', props.items.map((item) => h('li', { key: item.id }, slots.item?.({ item }))))

Passing slots to a child: the third argument to h(Component, ...) is an object of functions, or a single function for just the default slot:

h(DataTable, { rows }, {
  default: () => 'Body content',
  footer: ({ total }) => h('strong', `Total: ${total}`),
})

They must be functions so the child can call them lazily, during its own render and with its own slot props. That way the slot’s reactive dependencies are tracked by the child rather than the parent, so updates stay precise.

Because slots are just functions returning vnode arrays, a render function can inspect them: count the children passed to a <Tabs> component, read their props, wrap each one. A template can’t do that, and it’s one of the real reasons component libraries use render functions.

Functional components

For a small, stateless piece of markup, a component can be a plain function. It receives props and a context, and returns vnodes:

import { h } from 'vue'

function Heading(props, { slots }) {
  return h(`h${props.level}`, { class: 'heading' }, slots.default?.())
}
Heading.props = ['level']

It has no instance, no setup, and no state. It just renders. That suits wrappers like this, where the tag name itself is computed. (For a single dynamic tag in a template, <component :is="h${level}"> also works.)

JSX

Nested h calls get hard to read. JSX is an alternative syntax that compiles to the same thing. Vue supports it through a Babel plugin, set up in Vite with @vitejs/plugin-vue-jsx:

// vite.config.js
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default { plugins: [vue(), vueJsx()] }

For TypeScript, set "jsx": "preserve" and "jsxImportSource": "vue" in tsconfig.json so .tsx files get Vue’s JSX types. Since Vue 3.4, those types are no longer registered globally by default, so the jsxImportSource setting matters.

// Counter.tsx
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup(_, { slots }) {
    const count = ref(0)
    return () => (
      <div class="counter">
        <button onClick={() => count.value++}>+1</button>
        <span>{count.value}</span>
        {slots.default?.()}
      </div>
    )
  },
})

If you know React’s JSX, note the differences. Attributes are HTML names (class, for), not className and htmlFor. The Vue JSX plugin understands v-model and v-show. Slots are passed as an object of functions, either as the child expression or through a v-slots prop:

<DataTable rows={rows}>
  {{
    default: () => 'Body',
    footer: ({ total }: { total: number }) => <strong>Total: {total}</strong>,
  }}
</DataTable>

When to reach for this, and when not to

Templates are the default for good reason. The compiler can see which parts of a template are static and which are dynamic. It hoists static nodes out of the render function, tags each dynamic node with a patch flag saying exactly what can change (just the text, or just the class), and groups dynamic nodes into blocks so the runtime skips static content when diffing. A hand-written render function is opaque JavaScript, so the runtime has to diff all of it. Templates are also what Vapor mode builds on: it compiles templates straight to DOM operations with no virtual DOM, and hand-written render functions stay on the virtual DOM path.

Reach for render functions or JSX when:

  • the structure is genuinely computed (tag names, nesting depth, or component types decided at runtime) and <component :is> or v-for gets contorted;
  • you need to inspect or rearrange slot content, as in tabs, steppers, or table libraries;
  • you’re writing a library where a few lines of h replace a forest of conditional template branches;
  • your team strongly prefers JSX and accepts the trade-off.

What the video covers

Erik Hanchett gave a VueConf 2021 talk on render functions, and this video recaps it: what render functions are and why templates compile to them, the two styles of writing one, the h() function, applying a directive inside a render function, how slots work in render-function code, and two practical tips. The h() API it shows is unchanged in Vue 3.5. It doesn’t touch JSX, functional components, or the compiler optimizations you give up, which is why those sections are in the lesson. The follow-up under Go deeper builds a small app entirely in h(), including default and scoped slots.

Where this fits

This closes the reusing-logic group: composables for logic, VueUse for ready-made composables, directives for element behavior, plugins for app-wide setup, and render functions for when templates run out. Next come the components Vue ships with, starting with Transition and TransitionGroup.

Check yourself

  1. 01In a component whose setup returns () => h('p', count.value), what re-runs when count changes: setup or the returned function?

    Only the returned render function. setup runs once per component instance and creates count. Vue runs the render function inside a reactive effect, so reading count.value inside it tracks the dependency, and changing count re-runs the render function and patches the DOM.

  2. 02How do you pass a default slot and a named footer slot that receives { total } to a child component with h()?

    Pass an object of functions as the third argument: h(Child, null, { default: () => 'Body', footer: ({ total }) => h('span', `Total: ${total}`) }). Slots passed to components must be functions so the child can call them lazily, during its own render, with its own slot props.

  3. 03What is the render-function equivalent of <MyInput v-model="name" />?

    h(MyInput, { modelValue: name.value, 'onUpdate:modelValue': (value) => (name.value = value) }). v-model on a component is compiler sugar for a modelValue prop plus an update:modelValue event listener, and in a render function you write both out by hand.

  4. 04Why are templates usually faster to update than equivalent hand-written render functions?

    The template compiler can see which parts are static and which are dynamic. It hoists static nodes out of the render function, marks dynamic nodes with patch flags saying exactly what can change, and groups dynamic nodes into blocks, so the runtime skips static content when diffing. A hand-written render function is opaque JavaScript, so the runtime has to diff it fully.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark