The effect function to execute. Should contain reactive property access.
Effects are executed asynchronously when triggered to avoid immediate re-execution and to batch multiple changes together.
const state = reactive({ name: 'John' });
effect(() => {
console.log('Hello,', state.name); // Immediately logs: "Hello, John"
});
state.name = 'Jane'; // Effect will run in next microtask, not immediately
const state = reactive({ count: 0, doubled: 0 });
effect(() => {
state.doubled = state.count * 2;
});
state.count = 5;
console.log(state.doubled); // Still 0 - effect hasn't run yet
await 0; // Wait for microtask
console.log(state.doubled); // Now 10 - effect has run
const state = reactive({ a: 1, b: 2, sum: 0 });
effect(() => {
state.sum = state.a + state.b;
console.log('Sum updated:', state.sum);
});
// Multiple synchronous changes are batched, effect runs only once in next microtask, not twice
state.a = 10;
state.b = 20;
Create and immediately execute an effect function that tracks reactive dependencies
When the effect function runs, any reactive properties it accesses will be tracked. If those properties change later, the effect will be re-executed automatically in the next microtask.