Blog>
Snippets

Basic Reactive Effect with Vue's watchEffect

Create a reactive effect that watches a reactive source and logs the updated value each time it changes.
const { reactive, watchEffect } = Vue;

// Define a reactive state
const state = reactive({
    count: 0
});

// Create the watch effect
watchEffect(() => {
    // This will run immediately and whenever `state.count` changes
    console.log(`The count is: ${state.count}`);
});
Setting up a reactive state with a variable `count` and create a watch effect that logs the `count` value initially and every time it changes.
// Example interaction with the reactive state:
state.count++; // When this line runs, the console will log: 'The count is: 1'
Demonstrating how changing the `count` property on the reactive state triggers the watch effect to log the new value.