Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 87 ยท Reusability, Transitions and Styling

Render Functions and JSX

Learn Vue 3 render functions with h(), vnodes, dynamic tags, slots and functional components. See how JSX fits in and when templates are still the better choice.

Templates are how you write Vue components almost all the time, and they are the right default. But a template is only a convenient syntax: Vue's compiler turns it into a render function, a plain JavaScript function that returns a description of what to show. You can write that function yourself. Then you have the full power of JavaScript (loops, conditions, variables, helper functions) available at every point of the output, which is occasionally exactly what you need.

This lesson shows what the compiler produces, how to write h() calls by hand, how slots and functional components look in that style, and what JSX is. It ends with guidance on when it is worth leaving templates behind, which is less often than you might think.

flowchart LR
    T["Template<br/>(HTML-like syntax)"] -->|"compiler"| R["Render function"]
    R -->|"returns"| V["Virtual DOM nodes<br/>(vnodes)"]
    V -->|"patch"| D["Real DOM"]
    J["JSX or hand-written h()"] --> R

Whatever you write, Vue ends up with a render function that returns vnodes, and diffs them against the previous result to update the DOM.

Vnodes and h()

A vnode (virtual node) is a plain JavaScript object that describes one piece of UI: its type, its props and its children. The function that creates vnodes is h(), short for "hyperscript":

JavaScript
h(type, props, children)
  • type is a tag name such as "div", or a component.
  • props is an optional object of attributes, properties and event listeners: { class: "box", id: "a", onClick: handler }. Listeners are written as onClick, onInput and so on. You can omit props entirely when you only have children.
  • children is a string, an array of vnodes and strings, or (for components) a slot function or an object of slot functions.

You write a render function in two common ways: as the render() option, or by returning a function from setup(). The function returned from setup() is called again whenever reactive state it reads changes, exactly like a template.

Writing a component with h()

Several things to notice in this one example:

  • The <pre> shows that a vnode really is a small object: {"type":"p","props":{"class":"note"},"children":"Hello"}.
  • The heading tag is built with "h" + props.level. In a template you would need a <component :is> for that; in a render function it is ordinary string concatenation.
  • The list uses Array.map instead of v-for, and the key goes into the props, as with list rendering.
  • class accepts the same object, array and string forms as in a template (see class and style binding).
  • Inside a render function you read refs with .value, because nothing unwraps them for you the way a template does.

Components, slots and registered names

To render a component, pass the component object itself as the first argument: h(Heading, props, slots). Slots are passed as the third argument. A single function is the default slot, and an object of functions gives named slots; scoped slots receive their data as the function's argument:

JavaScript
h(Card, { title: "Report" }, {
  default: () => h("p", "Body text"),
  footer: ({ closed }) => h("small", closed ? "Closed" : "Open"),
});

The slot must be a function, not a ready-made vnode, so that Vue can run it at the right moment and track what it reads. Inside a component you reach the slots from the setup context: slots.default?.() returns the vnodes, or undefined when the parent passed nothing, which is why the optional call is a good habit (the example above can skip it because it always passes content).

For a component registered by name (see components) you look it up first with resolveComponent("MyButton"). Other template helpers have function equivalents too: withModifiers(handler, ["stop"]) for event modifiers and withDirectives(h("input"), [[vFocus]]) for custom directives. They are read-only here, because the examples on this site use components as plain objects.

Functional components

A functional component is a plain function that receives props and a context object ({ slots, attrs, emit }) and returns vnodes. It has no state, no lifecycle hooks and no this. It is a good fit for small presentational pieces.

Without a props declaration, a functional component receives all attributes as props. Declare props as a property on the function when you want Vue to separate real props from the remaining attributes, which then fall through to the root element as usual.

Functional components and a scoped slot

DataList does not know how items should look; the parent passes an item slot that builds a name and a Tag for each one. Press the button and the monitor flips between "sold out" and "5 in stock": the render function reads items.value and the stock numbers while it runs, so Vue re-runs it when they change.

The same markup in a template would read:

VUE
<DataList :items="items">
  <template #item="{ item, index }">
    <strong>{{ index + 1 }}. {{ item.name }}</strong>
    <Tag :tone="item.stock > 0 ? 'ok' : 'out'">
      {{ item.stock > 0 ? `${item.stock} in stock` : "sold out" }}
    </Tag>
  </template>
</DataList>

Compare the two. For this component the template is shorter and easier to scan, which is typical.

JSX in Vue

JSX is an XML-like syntax that a build step turns into h() calls, so you get the look of markup inside JavaScript. In Vue it is optional and needs the official plugin (@vitejs/plugin-vue-jsx in a Vite project). It cannot run on this site's runner, so this is read-only code:

JSX
// Counter.jsx
import { defineComponent, ref } from "vue";

export default defineComponent({
  props: { start: { type: Number, default: 0 } },
  setup(props) {
    const count = ref(props.start);

    return () => (
      <button class="counter" onClick={() => count.value++}>
        Clicked {count.value} times
      </button>
    );
  },
});

Vue's JSX differs from React's in a few ways: you write class and for, not className and htmlFor, and, as with any render function, you must write .value on refs. The plugin also supports directives such as v-model and v-show as attributes, and slots are passed as an object of functions. If you know JSX from React, the transition is small.

When to prefer which

Templates are the default for good reasons, and not only readability. The compiler can see your template as a whole, so it hoists static parts out of the render function, marks which bindings are dynamic with patch flags and skips work during updates. A hand-written render function cannot give Vue those hints, so Vue has to compare more.

Choose a render function or JSX when:

  • the structure is genuinely dynamic: a tag chosen at runtime, a component that renders arbitrary nested data, or a wrapper that transforms its slot's vnodes;
  • you build a library component where programmatic control matters more than template readability;
  • you are writing a tiny stateless helper (a functional component) and a separate file feels heavy;
  • your team already writes JSX and prefers keeping markup and logic in one place.

Stay with templates for ordinary application components, forms and pages. If you only want a dynamic tag, try <component :is="tag"> first, and for reusable logic prefer a composable. It is also fine to mix: a component's template can use child components that are written as render functions, and the reverse.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a vnode?

    h() returns a lightweight object describing what to render. Vue compares vnodes from successive renders and updates the real DOM only where they differ.
  2. 2. Which call correctly renders a component with a default slot?

    Slots must be functions (or an object of functions), so Vue can call them while rendering and track what they read. A function as the third argument is the default slot.
  3. 3. Inside a render function returned from setup(), how do you read a ref named count?

    Templates unwrap refs for you; render functions are plain JavaScript, so you read and write the .value property yourself.
  4. 4. Why are templates usually preferred over hand-written render functions for app components?

    Render functions are fully reactive and can render components. Templates are preferred because they are easier to read and the compiler adds optimizations that a hand-written function does not get.

Summary

  • Templates compile to render functions; a render function returns vnodes, which are plain objects, and Vue patches the DOM from them.
  • h(type, props, children) creates a vnode; listeners are onClick-style props, and refs need .value.
  • Components are passed as objects, and slots as functions or objects of functions; scoped slots receive their data as an argument.
  • Functional components are plain functions of (props, { slots, attrs, emit }); declare their props to separate props from attributes.
  • JSX compiles to h() and needs a plugin; use render functions or JSX for truly dynamic structure, and templates for most components.

Next: Teleport and KeepAlive