Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/wise-coins-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@preact/signals": patch
---

Make useComputed always use the initial compute function
9 changes: 5 additions & 4 deletions packages/preact/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,11 +421,12 @@ export function useSignal<T>(value?: T, options?: SignalOptions<T>) {
)[0];
}

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

function safeRaf(callback: () => void) {
Expand Down
55 changes: 54 additions & 1 deletion packages/preact/test/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ import {
Component,
} from "preact";
import type { ComponentChildren, FunctionComponent, VNode } from "preact";
import { useContext, useEffect, useRef, useState } from "preact/hooks";
import {
useContext,
useEffect,
useRef,
useState,
useCallback,
} from "preact/hooks";
import { setupRerender, act } from "preact/test-utils";

const sleep = (ms?: number) => new Promise(r => setTimeout(r, ms));
Expand Down Expand Up @@ -1001,4 +1007,51 @@ describe("@preact/signals", () => {
expect(spy).to.have.been.calledWith("willmount:1");
});
});

describe("useComputed", () => {
it("should keep using the compute initial compute function", async () => {
const s1 = signal(1);
const s2 = signal("a");

function App({ x }: { x: Signal }) {
const c = useComputed(() => {
return x.value;
});
return <span>{c.value}</span>;
}

render(<App x={s1} />, scratch);
expect(scratch.textContent).to.equal("1");

render(<App x={s2} />, scratch);
expect(scratch.textContent).to.equal("1");

s1.value = 2;
rerender();
expect(scratch.textContent).to.equal("2");
});

it("should not recompute when the compute function doesn't change and dependency values don't change", async () => {
const s1 = signal(1);
const spy = sinon.spy();

function App({ x }: { x: Signal }) {
const fn = useCallback(() => {
spy();
return x.value;
}, [x]);

const c = useComputed(fn);
return <span>{c.value}</span>;
}

render(<App x={s1} />, scratch);
expect(scratch.textContent).to.equal("1");
expect(spy).to.have.been.calledOnce;

rerender();
expect(scratch.textContent).to.equal("1");
expect(spy).to.have.been.calledOnce;
});
});
});