You can use the onUpdated lifecycle hook in Vue.js whenever there’s been a re-render of the component. A re-render occurs whenever you make some changes to the reactive data you’ve bound in the component. That means you’re calling onUpdated every time you make some state update.
This is somewhat like the watch method in Vue.js. Except, instead of observing a particular state, it’ll observe all the states in the component for a change.
Here’s an example to demonstrate the same. We have an input field with a reactive state named inputData.userInput. Whenver we make some changes to this state, onUpdate and onBeforeUpdate will be called. We’re calling onBeforeUpdate just before the onUpdate hook.
<script setup>
import { onBeforeUpdate, onUpdated, reactive } from "vue";
const inputData = reactive({
userInput: ''
})
onBeforeUpdate(() => {
console.log('onBeforeUpdate called!')
})
onUpdated(() => {
console.log('onUpdated called!')
})
</script>
<template>
<div>
<input type="text" v-model="inputData.userInput" />
</div>
</template>
//console output
HomeView.vue: onBeforeUpdate called!
HomeView.vue: onUpdated called!
Code language: HTML, XML (xml)
Warning! Please be careful while using the onUpdated lifecycle hook. Let’s say you’re updating a state x which changes a state y on update. And the state y changes the state x on update, then you’re practically creating an infinite loop of updates! In such a case you’ll see a long list of actions used in the onBeforeUpdate and onUpdated methods, followed by this warning message:
Here’s a situation which might cause the above warning:
<script setup>
import { onBeforeUpdate, onUpdated, reactive } from "vue";
const userData = reactive({
x: 1,
y: 1
})
onBeforeUpdate(() => {
console.log('onBeforeUpdate called!')
})
onUpdated(() => {
console.log('onUpdated called!')
userData.x = userData.x+userData.y
userData.y = userData.y+userData.x
})
</script>
<template>
<div>
{{userData.x}} {{userData.y}}
</div>
</template>
Code language: HTML, XML (xml)
If you have any doubts or suggestions, sound off in the comments section below!