signals
signals copied to clipboard
Proposal: use watcher
As discussed in #247, this PR introduces a new hook, useWatcher, which converts a non-signal value into a signal.
Motivation
Signals are a powerful primitive, but one main restriction of them is that signal dependencies can only be established between other signals. This means that deriving values between a non-signal and a signal can potentially not update correctly:
function Foo({ s, n }: { s: ReadonlySignal<number>, n: number }) {
const combined = useComputed(() => s.value * n * n);
// combined only recomputes if s is modified
return <p>{combined}</p>;
}
Specific scenarios where this limitation is apparent is when using third-party libraries that do not store state with signals. The useWatcher hook is a solution to this restriction, as it essentially wraps a non-signal value in a signal. This as a result allows for changes to the non-signal value to be seen by other signals:
function Foo({ s, n }: { s: ReadonlySignal<number>, n: number }) {
const $n = useWatcher(n);
const combined = useComputed(() => s.value * $n.value * $n.value);
// combined now updates correctly
return <p>{combined}</p>;
}
While this hook could just be created by end-users, the most optimal implementation of the useWatcher breaks typical React convention, which can lead to pitfalls for said end-users.
Implementation
While all current testcases are passing, one area of uncertainty is with the Preact adapter. Setting the signal .value in useWatcher may cause extra Component updates to trigger when they shouldn't, so some verification on that end would be appreciated.
Resolves #247
🦋 Changeset detected
Latest commit: 7169cb8f73357bf94abf6200f8d514fedbeed2eb
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 2 packages
| Name | Type |
|---|---|
| @preact/signals | Major |
| @preact/signals-react | Major |
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
Deploy Preview for preact-signals-demo ready!
| Name | Link |
|---|---|
| Latest commit | 7169cb8f73357bf94abf6200f8d514fedbeed2eb |
| Latest deploy log | https://app.netlify.com/sites/preact-signals-demo/deploys/63b6ef3768e05a0007fe34e0 |
| Deploy Preview | https://deploy-preview-266--preact-signals-demo.netlify.app |
| Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
Btw, i don't thinks its major release
I think it shouldn't be in adapter lib, it will have good fit inside of utility libs. I will create collection of hooks for signals