The initial data type. Defaults to a plain object.
Reactive context; defaults to the shared global context when
called without an explicit receiver. To isolate signals, bind or call with
a custom object: signal.call(myCtx, data).
The initial data. Defaults to an empty plain object.
A reactive Proxy that mirrors data, preserving array vs object shape.
// creates a reactive signal
const state = signal({
// reactive field
page: 1,
// computed reactive field
get left() {
return 100 - this.page;
},
// methods, bound to the proxy
nextPost() {
if (this.page < 100) this.page++;
},
prevPost() {
if (this.page > 1) this.page--;
},
async fetchPost() {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${this.page}`,
);
return await response.json();
},
});
Creates a reactive proxy around the given data object.
Property reads inside an active effect are automatically tracked. Nested plain objects and arrays are wrapped too; class instances,
Map,Set,Date, and objects with a null prototype are returned as is and are not reactive. An object always reads as the same proxy, wherever it is reached from, sostate.selected = state.items[0]keepsstate.selected === state.items[0]; a proxy is stored as its plain object. Wrapping an object a second time, or passing a signal tosignal(), returns the existing proxy and its context. Writing an index past the end of an array re-runs the effects that readlength; assigning a smallerlengthre-runs the effects that readlength, a dropped index, or the keys. Methods are returned bound to the proxy (cached, so a method reads as the same function each time, but not as the original); classes and built-in constructors (sostate.items.constructor === Array) are returned as is. Reading a read-only, non-configurable property (such as one of a frozen object) that holds a nested object, array, or method throws aTypeError; keep frozen data outside the signal. Defining a property withObject.defineProperty()does not re-run effects; assign it instead. Writes and deletions schedule one batched re-run per tick of the dependent effects: an effect re-runs once, however many of its properties changed.