preactjs / preact-www

:book: Preact documentation website.
https://preactjs.com
MIT License
356 stars 501 forks source link

Local effects with signals #902

Closed mindplay-dk closed 1 year ago

mindplay-dk commented 2 years ago

The "Local state with signals" section covers only useSignal and useComputed - it doesn't cover effects triggered by local signals.

Can we use normal useEffect for that?

Would you specify deps as e.g. signal or signal.value?

Or is this a part of the Signals story that has yet to unfold? 🙂

developit commented 2 years ago

We don't provide a version of effect() bound to component lifecycle yet, but are considering adding it in preactjs/signals#91. Once added, we'll document it.

In the meantime, you can use normal useEffect, it will just trigger a component render:

const count = useSignal(0);

// run every time count.value changes:
useEffect(() => {
  console.log(count.value);
}, [count.value]);

Alternatively, you can use the implementation we're likely to land - it's pretty short:

import { effect } from '@preact/signals';

// runs on mount, when any signal deps change, and cleans up on unmount:
function useSignalEffect(callback) {
  useEffect(() => effect(callback), []);
}

useSignalEffect(() => {
  console.log(count.value);
});
rschristian commented 1 year ago

useSignalEffect has landed, so I think this is good to close out.