Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
WatchEffect is triggered twice when watching a reactive object

If I run this code:

const state = reactive({
    title: '',
})

watchEffect(() => {
    console.log(state.title)
})

watchEffect is triggered and the console is outputting an empty string:

""

If I want to assign a new value to state.title, watchEffect is triggered twice. Is this behaviour expected or am I doing something wrong?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

According to the documentation, watchEffect

Runs a function immediately [emphasis added] while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.

So it is expected that it should run twice in this situation: once when it is first defined, and then again when the value changes.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As @MykWillis pointed out and is clearly stated in the docs, watchEffect runs immediately and on subsequent changes, exactly as watch with { immediate: true } would.

If you do not want the effect to run initially, don't use watchEffect, use watch instead:

const { createApp, watchEffect, reactive, toRefs, watch } = Vue;

createApp({
  setup() {
    const state = reactive({
      title: 'test',
    });

    watchEffect(() => {
      console.log('watchEffect', state.title)
    });

    watch(() => state.title, () => {
      console.log('watch', state.title)
    });

    watch(() => state.title, () => {
      console.log('watch.immediate', state.title)
    }, { immediate: true })
    
    return { ...toRefs(state) }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
  <input v-model="title">
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda