Skip to content

Commit ef60edb

Browse files
doc: extend the Using signals example with a bit more explanation and guidance
1 parent 91924a2 commit ef60edb

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

packages/signal-polyfill/readme.md

+20-4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ This is a polyfill for the `Signal` API.
88

99
### Using signals
1010

11+
* Use `Signal.State(value)` to create a single "cell" of data that can flow through the unidirectional state graph.
12+
* Use `Signal.Computed(callback)` to define a computation based on state or other computations flowing through the graph.
13+
1114
```js
1215
import { Signal } from "signal-polyfill";
1316
import { effect } from "./effect.js";
@@ -16,13 +19,26 @@ const counter = new Signal.State(0);
1619
const isEven = new Signal.Computed(() => (counter.get() & 1) == 0);
1720
const parity = new Signal.Computed(() => isEven.get() ? "even" : "odd");
1821

19-
effect(() => console.log(parity.get()));
22+
effect(() => console.log(parity.get())); // Console logs "even" immediately.
23+
setInterval(() => counter.set(counter.get() + 1), 1000); // Changes the counter every 1000ms.
24+
25+
// effect triggers console log "odd"
26+
// effect triggers console log "even"
27+
// effect triggers console log "odd"
28+
// ...
29+
```
30+
31+
The signal proposal does not include an `effect` API, since such APIs are often deeply integrated with rendering and batch strategies that are highly framework/library dependent. However, the proposal does seek to define a set of primitives that library authors can use to implement their own effects.
32+
33+
When working directly with library effect APIs, always be sure to understand the behavior of the `effect` implementation. While the signal algorithm is standardized, effects are not and may vary. To illustrate this, have a look at this code:
2034

21-
setInterval(() => counter.set(counter.get() + 1), 1000);
35+
```js
36+
counter.get(); // 0
37+
effect(() => counter.set(counter.get() + 1)); // Infinite loop???
38+
counter.get(); // 1
2239
```
2340

24-
> [!NOTE]
25-
> The signal proposal does not include an `effect` API, since such APIs are often deeply integrated with rendering and batch strategies that are highly framework/library dependent. However, the proposal does seek to define a set of primitives that library authors can use to implement their own effects.
41+
Depending on how the effect is implemented, the above code could result in an infinite loop. It's also important to note that running the effect, in this case, causes an immediate invocation of the callback, changing the value of the counter.
2642

2743
### Creating a simple effect
2844

0 commit comments

Comments
 (0)