-
-
Notifications
You must be signed in to change notification settings - Fork 95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
useSignal
should not use useMemo
#307
Comments
The implementation could be like the bellow. export function useSignal<T>(value: T) {
const $signal = useRef<Signal<T>>();
return $signal.current ??= signal<T>(value);
} |
At least for Preact hooks, utlizing the The |
In reality |
function useMyHook(someValue: SomeType) {
// value set during signal creation:
const signal = useSignal<SomeType>(someValue)
// update value if `someValue` changes, since `useMemo` hides that change:
signal.value = someValue
return computed(() => {
return doSomethingWith(signal.value)
})
}
function useSignal<T>(value: T) {
return useMemo(() => signal(value), [value])
}
Later
function MyComponent({ foo }) {
const fooSignal = useSignal(foo); // always "Foo1" unless we update it here
useEffect(() => {
if (someCondition(foo, bar)) {
fooSignal.value = foo
}
}, [foo])
return <div>foo: {foo}, fooSignal: {fooSignal.value}</div>
}
Further edit I retract this. A really simple use-case that requires a different |
I think there is no problem 1, but since a search led me here and I just figured this out, maybe my explanation will help others: This is all about lifetimes. The reason we have hooks is that parts of a component live longer than a render of that component. We want to re-render and get a view that's logically the same. 2 All we want for signals is that they have the same lifetime as the component. This can be achieved in different ways, which are all equivalent:
useState seems like the most idiomatic way to do this. A signal is a kind of state with more features and updated in a different way, so we don't want the second return value. Footnotes
|
I like this solution. It's logically correct and concise. |
The current implementation of
useSignal
usesuseMemo
.signals/packages/react/src/index.ts
Lines 217 to 219 in 325499c
React document says to write the code so that it still works without
useMemo
. Preact might be the same.Without
useMemo
,useSignal
will create a new signal instance every time when re-rendering occurs and lose the previous value.Also,
useComputed
usesuseMemo
. There's no problem I think.signals/packages/react/src/index.ts
Lines 221 to 225 in 325499c
The text was updated successfully, but these errors were encountered: