x-effect Directive

Run a side effect whenever any dependency changes – like a live watcher.

What is x-effect?

x-effect runs a JavaScript expression every time any of its reactive dependencies change. It’s like a live watcher or a computed property that performs side effects. Use it for logging, syncing, or updating third‑party libraries.

When to Use

Use x-effect when you need to run custom logic after data changes that isn't covered by other directives – for example, logging state changes, updating a chart, or synchronizing a non‑Alpine element.

Basic Example

Code
<div x-data="{ count: 0 }" x-effect="console.log('Count changed to', count)">
  <button @click="count++">+</button>
  <span x-text="count"></span>
</div>

Caution

  • Avoid expensive operations inside x-effect; it runs on every dependency change.
  • For watching a single property, $watch is more efficient.
  • x-effect tracks all reactive properties accessed inside its expression, so be mindful of unintended dependencies.
Helpful? Share this page!↑ Back to top