preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.71k stars 91 forks source link

Proposal: `untracked` api function #378

Closed betula closed 1 year ago

betula commented 1 year ago

Untracked

Necessary to implement a function that provides a possibility for disabling the tracking of dependencies.

It has already been implemented in Angular Signals and MobX.

Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function can, optionally, return a value. Angular16 docs untracked

Runs a piece of code without establishing observers. MobX docs untracked

What's the reason to use it?

For reading one signal without dependency creation the peek method already implement. Reading signals without subscribing to them

On the rare occasion that you need to write to a signal inside effect(fn), but don't want the effect to re-run when that signal changes, you can use .peek() to get the signal's current value without subscribing.

But it is not enough.

untracked function provides the possibility for the reaction pattern:

function reaction(sender, listener) {
  effect(() => {
    const value = sender();
    untracked(() => {
      listener(value);
    });
  }
}

In that pattern, you have a way to control your dependencies. The reaction will collect dependencies only from the sender function, and react only on them.

Many thanks to you, your signals implementation is amazing, I think the best at the moment.

XantreDev commented 1 year ago

I really need this functionality, too. In case of compositibility and easibility of usage, in some cases it's easier to use solidjs like Accessor type Accessor<T> = () => T Because its easy way to define lazy computation that will executed on demand. And you don't need to rely on rules of hooks. But for more flexible usage of this pattern, i need a way to turn off deps tracking on consumer side image

XantreDev commented 1 year ago

380