useSignalEffect + React = cycle #327
Unanswered
jamesarosen
asked this question in
Q&A
Replies: 1 comment
-
I can move the cleanup into useSignalEffect(() => {
if (timer.value == null) {
timer.value = setInterval(() => {
time.value = new Date()
}, 1000)
}
})
useEffect(() => {
return () => {
clearInterval(timer.value)
timer.value = null
}
}, [timer]) That works fine. I don't know that it reads better or worse. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a hook that sets up some state and tears it down. I tried using
useSignalEffect
to do this, but I ran into a problem.If I set
theSignal.value = null
in my cleanup function, it triggers an infinite cycle because Preact detects a change, reruns myuseSignalEffect
hook, and reinitializes the state.But if I don't set
theSignal.value = null
in my cleanup function, the hook remembers the signal state after cleanup and doesn't reinitialize on the re-render. This is particularly noticeable with React's<StrictMode>
, but it also happens if something external to the hook passes in a new value that should cause the hook to tear down the old state and initialize new state.An example broken hook:
A version that works using React's
useEffect
plus Preact'seffect
:Demo: https://stackblitz.com/edit/react-signal-effect-cycle?file=App.tsx
Beta Was this translation helpful? Give feedback.
All reactions