This question is not an issue, it is for educational purpose.
I was trying out effect and useSignalEffect from @preact/signals-react in react application. Problem is i see effect and useSignalEffect have same behaviour they both run when the subscribed signal changes. Could anybody clearify on whats the difference between them.
Example I have used:
import React from 'react'
import {effect, useSignal,useSignalEffect } from '@preact/signals-react'
export default function ComputedSignalExample() {
const count = useSignal(0);
useSignalEffect(() => {
console.log(`From useSignalEffect: ${count}`);
});
effect(() => {
console.log(`From Effect: ${count}`);
});
return (
<div>
<p>The current count is: {count}</p>
<button onClick={() => count.value++}>Increment</button>
</div>
);
}
From Effect: 0
From useSignalEffect: 0
From Effect: 1
From useSignalEffect: 1
From Effect: 2
From useSignalEffect: 2
I used useSignalEffect with a dependency array, to see if it might have same setup as useEffect react hook, but seems like, it doesn't care about dependency array.
useSignalEffect(() => {
console.log('From useSignalEffect');
},[count]);
Also tried this, but no effect:
useSignalEffect(() => {
console.log('From useSignalEffect');
},[count.value]);
The docs explicitly state what this is for:
If you need to instantiate new signals or create new side effects on signal changes inside your components, you can use the
useSignal,useComputedanduseSignalEffecthooks.
https://github.com/preactjs/signals/tree/main/packages/react#hooks
Don't use effect in components, it will be recreated (and resubscribe) upon every single rerender of your component. For a console.log(), this won't have much of an impact, but heavier effects could.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With