Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing callback to custom react hook

Tags:

react-hooks

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

like image 494
tgk Avatar asked Sep 06 '25 21:09

tgk


1 Answers

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)
  }, [])
}
like image 182
Ori Drori Avatar answered Sep 11 '25 02:09

Ori Drori