Effects
Run side effects in response to signal changes. Effects handle everything that isn't just returning UI.
What Are Effects?
Effects are functions that run automatically when their dependencies change. They're for side effects: things like:
- Fetching data
- Setting up subscriptions
- Updating the document title
- Logging
- Syncing with external systems
import { signal, effect } from 'what-framework';
const count = signal(0);
// Runs immediately, then re-runs when count changes
effect(() => {
console.log('Count is now:', count());
});
count.set(5); // Logs "Count is now: 5" on the next microtask
How Effects Work
When you create an effect:
- The function runs immediately
- What tracks which signals are read during execution
- When any of those signals change, the effect is queued and re-runs on the next microtask
const a = signal(1);
const b = signal(2);
effect(() => {
console.log(a() + b()); // Tracks both a and b
});
a.set(10);
b.set(20);
// Nothing logged yet. One re-run on the next microtask, logging 30
When effects run
Only the very first run is synchronous. After that a write queues the effect and the queue is drained on the next microtask, so several writes in the same tick produce a single re-run with the final values. Wrap the writes in batch() to have that run happen before the block returns, or call flushSync() to drain the queue on the spot. Both are exported from what-framework.
Do not build anything on top of the exact timing. What promotes some single-dependency effects to a faster inline path once their dependency set is proven stable, so an effect that ran on a microtask earlier may run synchronously later. In a test, always await a microtask or call flushSync() before asserting.
No dependency arrays
Unlike React's useEffect(fn, [deps]), What effects auto-track. Every signal read inside the function becomes a dependency automatically. You never need to maintain a deps array, and you'll never have stale closure bugs.
What's own useEffect auto-tracks the same way. Given a dependency array, it re-runs only for the accessors listed ([count], never [count()], which reports ERR_EFFECT_DEP_NOT_FUNCTION), and [] runs it once after mount. If you only need code to run once on mount, onMount says so most directly.
Cleanup Functions
Effects can return a cleanup function that runs before the next execution or when the effect is disposed:
effect(() => {
const handler = () => console.log('resize');
window.addEventListener('resize', handler);
// Cleanup: remove the listener
return () => {
window.removeEventListener('resize', handler);
};
});
Common uses for cleanup:
- Removing event listeners
- Clearing timers/intervals
- Canceling network requests
- Closing connections
Effects in a component
A component is an owner. An effect() created in its body belongs to it, and is disposed, cleanup included, when the component goes: when a reactive region, a list row or a route lets it go, or when the function mount() returns unmounts the tree. An effect created inside another effect's run belongs to that run the same way, and is disposed before the outer effect runs again.
import { effect, onCleanup } from 'what-framework';
function Widget({ userId }) {
effect(() => {
const id = setInterval(() => console.log('watching', userId()), 1000);
onCleanup(() => clearInterval(id)); // before the next run, and when Widget goes
});
return <div />;
}
An effect created outside any owner (at module scope, in an event handler, a timer, or after an await) lives until you call the disposer effect() returns. At module scope that is by design: it lives for the life of the page, and most of the examples below are that kind.
Best Practices
- Keep effects focused. One effect, one purpose.
- Always clean up. If you add a listener, remove it in cleanup.
- Prefer computed for derived values. Effects are for side effects only.
- Don't modify signals you're reading. An effect that writes a signal it also reads re-triggers itself, and What stops it after 100 rounds and reports
ERR_INFINITE_EFFECT. Usepeek(),untrack(), or the updater formcount.set(c => c + 1), none of which subscribe. - Dispose effects you create outside an owner. An effect created in a component body or an effect's run is disposed with it. One created in an event handler, a timer or after an
awaitlives until you call the disposereffect()returns. - Use
onMountfor one-time setup. Don't useeffectwhen you just need code to run once. - Handle errors. Wrap async code in try/catch.