What Is a Functional Component in Vue?

Vue functional components are simple components that usually have no state and only turn their input into output. They are designed with an approach close to functional programming: they need no state management and produce output from the data they receive — one of the core principles of functional programming.
In Vue 3 a functional component is a plain function that receives props and a context (attrs, slots, emit) and returns a virtual DOM node. It has no state and no component instance (this).
import { createApp, h } from 'vue';
// Vue 3: a functional component is a plain function of props and context
function MessageBox(props, { emit }) {
return h('div', [
h('p', props.message),
h('button', { onClick: () => emit('select') }, 'Click me'),
]);
}
MessageBox.props = ['message'];
MessageBox.emits = ['select'];
createApp({
render: () =>
h(MessageBox, {
message: 'Hello, I am a functional component!',
onSelect: () => console.log('The button was clicked'),
}),
}).mount('#app');MessageBox produces its output only from the message prop it receives and reports the click to its parent with emit.
Note (Vue 2): In Vue 2, functional components were declared with the functional: true option or <template functional>. That option was removed in Vue 3; the old syntax below works only in Vue 2 projects.
<template functional>
<div>
<p>{{ props.message }}</p>
<button @click="props.onClick">Click me</button>
</div>
</template>
<script>
export default {
functional: true,
props: {
message: String,
onClick: Function,
},
};
</script>In Vue 2, functional components were noticeably faster than regular ones. In Vue 3, regular components got so much faster that the difference is negligible, so functional components are recommended only for genuinely simple, stateless pieces.
Have a question about this article? Write to me


