Is there a way to use a preact signals effect function, in a way where I can choose what signals I want to subscribe?

95 Views Asked by At

I have this code.

effect(() => {
        productsShoes.value = shoes.value
})

I want to, everytime only, shoes.value is changed, trigger this effect. The way that is, its re-rendering, either both of signals are changed.

The logic that I want to achieve is like this with useEffect reacts hook:

    useEffect(() => {
        productsShoes.value = shoes.value
    }, [shoes.value])

First of all, thank you for your attention!

1

There are 1 best solutions below

0
On

To run arbitrary code in response to signal changes, we can use effect(fn). Similar to computed signals, effects track which signals are accessed and re-run their callback when those signals change. If the callback returns a function, this function will be run before the next value update. Unlike computed signals, effect() does not return a signal - it's the end of a sequence of changes.

[...]

When responding to signal changes within a component, use the hook variant: useSignalEffect(fn).

https://preactjs.com/guide/v10/signals/#effectfn

which means that for your case prefer useSignalEffect, no need to pass any dependency, it will already track your changes and run automatically