Course contentsShow
← JavaScript
Lesson 2120 of 2,72344. Reactive PatternsFree lesson

Effects and Side Effects

Running side effects automatically when signal values change, using effect functions to react to state without manual subscriptions.

Effects and Side Effects

You'll learn how to run code automatically whenever signal values change, without manually subscribing to updates.

What Are Effects?

In reactive systems, an effect is a function that runs automatically when the signals it depends on change. Think of it like a motion-sensor light: you don't manually flip the switch—the light just responds when it detects movement. Effects let you react to state changes without writing explicit subscription code.

Effects bridge the gap between reactive state (signals) and the outside world—things like updating the DOM, logging to the console, or making network requests.

How Effects Work

When you create an effect, the system tracks which signals are read during its first execution. From then on, whenever any of those signals change, your effect automatically re-runs:

// Assuming a simple signal library
const count = signal(0);

// This effect runs automatically when count changes
effect(() => {
  console.log(`Count is now: ${count.value}`);
});
// Logs: "Count is now: 0"

count.value = 5;
// Automatically logs: "Count is now: 5"

The effect function "subscribes" to count behind the scenes—no manual observer registration needed.

Why "Side Effects"?

In functional programming, a side effect is any operation that affects something outside the function's return value—like DOM updates, console logs, or API calls. Effects in reactive systems are designed for side effects. They're where your reactive data touches the real world.

Unlike computed signals (which derive new values), effects exist purely to do something when state changes.

Key Takeaway: Effects automatically run side-effect code when signals change, eliminating manual subscription management and creating a declarative way to respond to state updates.