passing callback to custom react hook

Viewed 773

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())

1 Answers

Set the callback on a ref, and then the useEffect() would not be called whenever the callback changes:

const useMyHook(callback){ 
  const cb = useRef();

  cb.current = callback;

  React.useEffect(() => {
    const worker = /// create worker
    worker.onmessage = (...args) => cb.current(...args);
  }, [])
}
Related