Reputation: 71
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]);
Upvotes: 4
Views: 3201
Reputation: 256
The difference is in scope. You would use effect() when you create a side effect that can be used anywhere in your project, but you would use useSignalEffect() when you want to create an effect specific specifically limited to within the component.
Upvotes: 0
Reputation: 2967
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
,useComputed
anduseSignalEffect
hooks.
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.
Upvotes: 4