Skip to content

Effects

Datastar provides two powerful tools for derived state and side effects. Effects run code in response to signal changes. Both help keep your reactive interfaces clean and efficient.

Effects

data-effect (Datastar)

An effect runs code whenever signals it references change. Unlike computed signals, effects don't return a value—they perform side effects:

blade
<div data-signals="{count: 0}">
    <div data-effect="console.log('Count changed to:', $count)"></div>

    <button data-on:click="$count = $count + 1">
        Increment
    </button>
</div>

Every time count changes, the message logs to the console.

Side Effects

Effects are useful for:

  • Logging and debugging
  • Synchronizing with external libraries
  • Analytics tracking
  • Local storage persistence

Common Patterns

Analytics Tracking

blade
<div data-signals="{
    currentPage: 'home',
    timeOnPage: 0
}">
    <div data-effect="
        if ($currentPage) {
            fetch('/analytics/page-view', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({page: $currentPage, timestamp: Date.now()})
            });
        }
    "></div>

    <button data-on:click="$currentPage = 'about'">Go to About</button>
</div>

Tracks page views automatically when the page changes.

Persistence to Local Storage

blade
<div data-signals="{
    notes: localStorage.getItem('notes') || ''
}">
    <div data-effect="localStorage.setItem('notes', $notes)"></div>

    <textarea
        data-bind="notes"
        rows="10"
        placeholder="Your notes are saved automatically...">
    </textarea>
</div>

Notes persist across page reloads.

Synchronize with External Library

blade
<div data-signals="{chartData: []}">
    <div data-effect="
        if (window.myChart) {
            window.myChart.data.datasets[0].data = $chartData;
            window.myChart.update();
        }
    "></div>

    <canvas id="myChart"></canvas>
</div>

Updates a Chart.js chart whenever signal data changes.

Learn More