I have a custom hook that creates a web worker and registers a callback with the worker:
const useMyHook(callback){ 
  React.useEffect(() => {
    let worker = /// create worker
    worker.onmessage = callback
  }, [callback])
}
to use the hook, the user has to know to wrap the callback in React.useCallback or each render will create a new worker. 
const callback = React.useCallback(() => doSomething())
useMyHook(callback)
How can I update my hook so the user can simply pass an anonymous func useMyHook(() => doSomething())
Set the callback on a ref, and update it in another useEffect block.
Remove the callback's  dependency of the worker's useEffect(), and call the callback from the cb.current.
const useMyHook(callback){ 
  const cb = useRef(callback)
  
  React.useEffect(() => {
    cb.current = callback
  })
  React.useEffect(() => {
    const worker = /// create worker
    worker.onmessage = (...args) => cb.current(...args)
  }, [])
}
                        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