4 ms·
Great comparison writeup! However, I do feel some of the points made are weak and seem to be rushing to conclusion. In the React hook worker code you do not re
by kushan2020 6y ago
Great comparison writeup! However, I do feel some of the points made are weak and seem to be rushing to conclusion.
In the React hook worker code you do not really need to use the `ref` and you can do something like:
```
function useWorker(currentUser, setCurrentPom) {
const [worker] = useState(() => new Worker(workerURL))
useEffect(() => {
const onMessage = (event) => {
if (event.data.name === 'tick') {
setCurrentPom((currentPom) => ({
...currentPom,
secondsRemaining: event.data.counter,
}))
} else if (event.data.name === 'start') {
// More branches removed here to save space...
}
}
worker.addEventListener('message', onMessage)
return () => {
worker.removeEventListener('message', onMessage)
}
}, [currentUser, setCurrentPom])
return worker
}
```
The reason it works is that `useState` allows you to lazy load something.
You mention two points which make svelte easier, but I would challenge you on those:
> We don't have to keep the worker in useRef, and can just assign it to a variable.
As per my thoughts above you do not need useRef, in fact you just separated the whole worker logic into a separate function which gives us separation of concern and better readability.
> We can pull the event listener code out into a function more easily, as that function won't then become a dependency to a useEffect - at which point we will have to wrap it in useCallback.
I am not sure I fully understand this. But if you are talking about wrapping the event listener code into a function, you can do that and you do not need to wrap it in a callback. Though, I am not sure what we gain out of abstracting the event handling part.