Effects
Run side effects when reactive values change
Effects are functions that run when the reactive values they depend on change. Use them for side effects like logging, DOM manipulation, or data fetching.
Creating an Effect
Use the effect function to create an effect:
import { reactive, effect } from 'hydroxide'
const count = reactive(0)
effect(() => {
console.log('count is now', count())
})When count changes, the effect re-runs and logs the new value.
Automatic Dependency Tracking
Hydroxide automatically tracks which reactives you read inside an effect. You don't need to specify dependencies manually:
Only the reactives you actually read inside the effect are tracked. If a reactive isn't read, changes to it won't trigger the effect.
Its also worth mentioning how this works - The first time effect runs on component mount, the Hydroxide runtime detects which reactives are called/read inside the effect and then whenever any of those reactives change later on, the effect will re-run. When component is unmounted, the effect unsubscribes from all the reactives it was tracking.
import { reactive, effect } from 'hydroxide'; function Example() { const countA = reactive(0); const countB = reactive(0); // Only tracks countA - ignores countB changes // open the console to see the logs effect(() => { console.log('Counter A updated:', countA()); }); function incrementA() { countA.set(countA() + 1); } function incrementB() { countB.set(countB() + 1); } return ( <div class="container"> <button on-click={incrementA} class="primary-button"> A is {countA()} </button> <button on-click={incrementB} class="primary-button"> B is {countB()} </button> </div> ); } export default Example;