Skip to content

Add watched and unwatched #634

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tough-rice-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@preact/signals-core": minor
"@preact/signals": minor
"@preact/signals-react": minor
---

Add an option to specify a watched/unwatched callback to a signal
40 changes: 25 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,16 @@ npm install @preact/signals-react
npm install @preact/signals-core
```

- [Guide / API](#guide--api)
- [`signal(initialValue)`](#signalinitialvalue)
- [`signal.peek()`](#signalpeek)
- [`computed(fn)`](#computedfn)
- [`effect(fn)`](#effectfn)
- [`batch(fn)`](#batchfn)
- [`untracked(fn)`](#untrackedfn)
- [Preact Integration](./packages/preact/README.md#preact-integration)
- [Hooks](./packages/preact/README.md#hooks)
- [Rendering optimizations](./packages/preact/README.md#rendering-optimizations)
- [Attribute optimization (experimental)](./packages/preact/README.md#attribute-optimization-experimental)
- [React Integration](./packages/react/README.md#react-integration)
- [Hooks](./packages/react/README.md#hooks)
- [Rendering optimizations](./packages/react/README.md#rendering-optimizations)
Comment on lines -30 to -36
Copy link
Member

@rschristian rschristian Jun 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only noticed now, but what was the reason for removing this? It was pretty convenient and directed users to the correct place for their specific use (even when published, NPM will link to the correct directory back here).

Especially problematic for React users, of which we've had so many who thought they could just install & match the APIs listed below.

Edit: Maybe it'd be better to finally split the repo root ReadMe from the core ReadMe. Will take a look at that.

- [License](#license)
- [Signals](#signals)
- [Installation:](#installation)
- [Guide / API](#guide--api)
- [`signal(initialValue)`](#signalinitialvalue)
- [`signal.peek()`](#signalpeek)
- [`computed(fn)`](#computedfn)
- [`effect(fn)`](#effectfn)
- [`batch(fn)`](#batchfn)
- [`untracked(fn)`](#untrackedfn)
- [License](#license)

## Guide / API

Expand All @@ -58,6 +53,21 @@ counter.value = 1;

Writing to a signal is done by setting its `.value` property. Changing a signal's value synchronously updates every [computed](#computedfn) and [effect](#effectfn) that depends on that signal, ensuring your app state is always consistent.

You can also pass options to `signal()` and `computed()` to be notified when the signal gains its first subscriber and loses its last subscriber:

```js
const counter = signal(0, {
watched: function () {
console.log("Signal has its first subscriber");
},
unwatched: function () {
console.log("Signal lost its last subscriber");
},
});
```

These callbacks are useful for managing resources or side effects that should only be active when the signal has subscribers. For example, you might use them to start/stop expensive background operations or subscribe/unsubscribe from external event sources.

#### `signal.peek()`

In the rare instance that you have an effect that should write to another signal based on the previous value, but you _don't_ want the effect to be subscribed to that signal, you can read a signals's previous value via `signal.peek()`.
Expand Down
2 changes: 2 additions & 0 deletions mangle.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
"cname": 6,
"props": {
"core: Node": "",
"$_watched": "W",
"$_unwatched": "Z",
"$_source": "S",
"$_prevSource": "p",
"$_nextSource": "n",
Expand Down
59 changes: 45 additions & 14 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ declare class Signal<T = any> {
/** @internal */
_targets?: Node;

constructor(value?: T);
constructor(value?: T, options?: SignalOptions<T>);

/** @internal */
_refresh(): boolean;
Expand All @@ -250,6 +250,12 @@ declare class Signal<T = any> {
/** @internal */
_unsubscribe(node: Node): void;

/** @internal */
_watched?(this: Signal<T>): void;

/** @internal */
_unwatched?(this: Signal<T>): void;

subscribe(fn: (value: T) => void): () => void;

valueOf(): T;
Expand All @@ -266,6 +272,11 @@ declare class Signal<T = any> {
set value(value: T);
}

export interface SignalOptions<T = any> {
watched: (this: Signal<T>) => void;
unwatched: (this: Signal<T>) => void;
}

/** @internal */
// @ts-ignore: "Cannot redeclare exported variable 'Signal'."
//
Expand All @@ -274,11 +285,13 @@ declare class Signal<T = any> {
//
// The previously declared class is implemented here with ES5-style prototypes.
// This enables better control of the transpiled output size.
function Signal(this: Signal, value?: unknown) {
function Signal(this: Signal, value?: unknown, options?: SignalOptions) {
this._value = value;
this._version = 0;
this._node = undefined;
this._targets = undefined;
this._watched = options?.watched;
this._unwatched = options?.unwatched;
}

Signal.prototype.brand = BRAND_SYMBOL;
Expand All @@ -288,12 +301,18 @@ Signal.prototype._refresh = function () {
};

Signal.prototype._subscribe = function (node) {
if (this._targets !== node && node._prevTarget === undefined) {
node._nextTarget = this._targets;
if (this._targets !== undefined) {
this._targets._prevTarget = node;
}
const targets = this._targets;
if (targets !== node && node._prevTarget === undefined) {
node._nextTarget = targets;
this._targets = node;

if (targets !== undefined) {
targets._prevTarget = node;
} else {
untracked(() => {
this._watched?.call(this);
});
}
}
};

Expand All @@ -306,12 +325,19 @@ Signal.prototype._unsubscribe = function (node) {
prev._nextTarget = next;
node._prevTarget = undefined;
}

if (next !== undefined) {
next._prevTarget = prev;
node._nextTarget = undefined;
}

if (node === this._targets) {
this._targets = next;
if (next === undefined) {
untracked(() => {
this._unwatched?.call(this);
});
}
}
}
};
Expand Down Expand Up @@ -392,10 +418,10 @@ Object.defineProperty(Signal.prototype, "value", {
* @param value The initial value for the signal.
* @returns A new signal.
*/
export function signal<T>(value: T): Signal<T>;
export function signal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function signal<T = undefined>(): Signal<T | undefined>;
export function signal<T>(value?: T): Signal<T> {
return new Signal(value);
export function signal<T>(value?: T, options?: SignalOptions<T>): Signal<T> {
return new Signal(value, options);
}

function needsToRecompute(target: Computed | Effect): boolean {
Expand Down Expand Up @@ -515,19 +541,21 @@ declare class Computed<T = any> extends Signal<T> {
_globalVersion: number;
_flags: number;

constructor(fn: () => T);
constructor(fn: () => T, options?: SignalOptions<T>);

_notify(): void;
get value(): T;
}

function Computed(this: Computed, fn: () => unknown) {
function Computed(this: Computed, fn: () => unknown, options?: SignalOptions) {
Signal.call(this, undefined);

this._fn = fn;
this._sources = undefined;
this._globalVersion = globalVersion - 1;
this._flags = OUTDATED;
this._watched = options?.watched;
this._unwatched = options?.unwatched;
}

Computed.prototype = new Signal() as Computed;
Expand Down Expand Up @@ -677,8 +705,11 @@ interface ReadonlySignal<T = any> {
* @param fn The effect callback.
* @returns A new read-only signal.
*/
function computed<T>(fn: () => T): ReadonlySignal<T> {
return new Computed(fn);
function computed<T>(
fn: () => T,
options?: SignalOptions<T>
): ReadonlySignal<T> {
return new Computed(fn, options);
}

function cleanupEffect(effect: Effect) {
Expand Down
70 changes: 70 additions & 0 deletions packages/core/test/signal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,45 @@ describe("signal", () => {
});
});

describe(".(un)watched()", () => {
it("should call watched when first subscription occurs", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = signal(1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
unsubscribe();
unsubscribe2();
expect(unwatched).to.be.calledOnce;
});

it("should allow updating the signal from watched", async () => {
const calls: number[] = [];
const watched = sinon.spy(() => {
setTimeout(() => {
s.value = 2;
});
});
const unwatched = sinon.spy();
const s = signal(1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = s.subscribe(() => {
calls.push(s.value);
});
expect(watched).to.be.calledOnce;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
await new Promise(resolve => setTimeout(resolve));
unsubscribe();
unsubscribe2();
expect(unwatched).to.be.calledOnce;
expect(calls).to.deep.equal([1, 2]);
});
});

it("signals should be identified with a symbol", () => {
const a = signal(0);
expect(a.brand).to.equal(Symbol.for("preact-signals"));
Expand Down Expand Up @@ -1064,6 +1103,37 @@ describe("computed()", () => {
expect(spy).not.to.be.called;
});

describe(".(un)watched()", () => {
it("should call watched when first subscription occurs", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = computed(() => 1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
unsubscribe();
unsubscribe2();
expect(unwatched).to.be.calledOnce;
});

it("should call watched when first subscription occurs w/ nested signal", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = signal(1, { watched, unwatched });
const c = computed(() => s.value + 1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = c.subscribe(() => {});
expect(watched).to.be.calledTwice;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledTwice;
unsubscribe2();
unsubscribe();
expect(unwatched).to.be.calledTwice;
});
});

it("should consider undefined value separate from uninitialized value", () => {
const a = signal(0);
const spy = sinon.spy(() => undefined);
Expand Down
14 changes: 9 additions & 5 deletions packages/preact/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Signal,
type ReadonlySignal,
untracked,
SignalOptions,
} from "@preact/signals-core";
import {
VNode,
Expand Down Expand Up @@ -382,17 +383,20 @@ Component.prototype.shouldComponentUpdate = function (
return false;
};

export function useSignal<T>(value: T): Signal<T>;
export function useSignal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function useSignal<T = undefined>(): Signal<T | undefined>;
export function useSignal<T>(value?: T) {
return useMemo(() => signal<T | undefined>(value), []);
export function useSignal<T>(value?: T, options?: SignalOptions<T>) {
return useMemo(
() => signal<T | undefined>(value, options as SignalOptions),
[]
);
}

export function useComputed<T>(compute: () => T) {
export function useComputed<T>(compute: () => T, options?: SignalOptions<T>) {
const $compute = useRef(compute);
$compute.current = compute;
(currentComponent as AugmentedComponent)._updateFlags |= HAS_COMPUTEDS;
return useMemo(() => computed<T>(() => $compute.current()), []);
return useMemo(() => computed<T>(() => $compute.current(), options), []);
}

function safeRaf(callback: () => void) {
Expand Down
17 changes: 12 additions & 5 deletions packages/react/runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
effect,
Signal,
ReadonlySignal,
SignalOptions,
} from "@preact/signals-core";
import {
useRef,
Expand Down Expand Up @@ -384,16 +385,22 @@ export function useSignals(usage?: EffectStoreUsage): EffectStore {
return _useSignalsImplementation(usage);
}

export function useSignal<T>(value: T): Signal<T>;
export function useSignal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function useSignal<T = undefined>(): Signal<T | undefined>;
export function useSignal<T>(value?: T) {
return useMemo(() => signal<T | undefined>(value), Empty);
export function useSignal<T>(value?: T, options?: SignalOptions<T>) {
return useMemo(
() => signal<T | undefined>(value, options as SignalOptions),
Empty
);
}

export function useComputed<T>(compute: () => T): ReadonlySignal<T> {
export function useComputed<T>(
compute: () => T,
options?: SignalOptions<T>
): ReadonlySignal<T> {
const $compute = useRef(compute);
$compute.current = compute;
return useMemo(() => computed<T>(() => $compute.current()), Empty);
return useMemo(() => computed<T>(() => $compute.current(), options), Empty);
}

export function useSignalEffect(cb: () => void | (() => void)) {
Expand Down