$watch Magic Method
Watch a specific property and run a callback when it changes.
What is $watch?
$watch is a method that lets you observe a specific data property and execute a function whenever its value changes. It's perfect for validations, side effects, or syncing with non‑Alpine code.
When to Use
Use $watch when you need to react to a single property change without the overhead of x-effect. Examples: validating an input, logging a value, or updating a dependent state.
Basic Example
<div x-data="{ count: 0 }" x-init="$watch('count', value => console.log('New count:', value))">
<button @click="count++">+</button>
<span x-text="count"></span>
</div>Deep Watching Objects
By default, $watch only watches the top‑level property. To watch nested changes inside an object or array, you need to watch a computed property or use $watch with a function that returns the value.
<div x-data="{ user: { name: 'John' } }" x-init="$watch('user', value => console.log(value), true)">
<input x-model="user.name">
</div>💡 Tip
If you need to watch multiple properties, you can either call $watch multiple times or use x-effect which automatically tracks all accessed properties.