Vue & Nuxt Tips
·
1 min read
·257 views
Since Nuxt 3.9 you can use the useOnce composable to run a given function or block of code once during server-side rendering or client-side navigation.
This is useful if you want to run a function only once during the initial render of a page. For example, you might want to log a certain event or set up a global state that should only be initialized once.
Let's take a look at an example:
app.vue
<script setup lang="ts">
await callOnce(async () => {
console.log('This will only be logged once')
})
</script>
Two things to note:
callOncedoesn't return anything, so you can't use it to return a value or promise.- You need to the
callOncecomposable in a setup function, plugin or route middleware because it needs to access the Nuxt payload.

