I have a scenario that I keep running into: I have an expensive function with a callback that’s wrapped in a useEffect. In this case, subscribing to a broadcast. I’d like to avoid re-subscribing every time the callback closure changes, and I was wondering how to do that properly.
For example, events.on/off
get called every time a state changes:
const cb = useCallback( () => {
fn( foo, bar, baz )
}, [fn, foo, bar, baz])
useEffect( () => {
events.on( "the-event", () => {
cb()
})
return () => events.off("the-event")
}, [events, cb])
Can I do something like the below with useRef to avoid re-subscribing:
const cb = useCallback( () => {
...
}, [fn, foo, bar, baz])
const ref = useRef(cb)
useEffect( () => {
events.on( "the-event", () => {
ref.current()
})
return ...
}, [events, ref])
1